2012-10-26 68 views
1

有人能告诉我为什么这个插入失败,但不给我一个错误?我该如何解决?合并不插入。没有错误

merge table1 as T1 
using(select p.1,p.2,p.3,p.4,p.5 from @parameters p 
inner join table1 t2 
on p.1 = t2.1 
and p.2 = t2.2 
and p.3 = t2.3 
and p.4 = t2.4) as SRC on SRC.2 = T1.2 
when not matched then insert (p.1,p.2,p.3,p.4,p.5) 
values (SRC.1,SRC.2,SRC.3,SRC.4,SRC.5) 
when matched then update set t1.5 = SRC.5; 

T1表格当前为空,因此没有任何内容可以匹配。参数表中确实有数据。我只需要修改这个合并,以便在决定做什么之前检查所有4个字段。

回答

0

其实,你可以使用一个变量表。检查出来:

MERGE Target_table AS [Target] 
    USING @parameters AS [Source] 
    ON (

     [Target].col1 = [Source].col1 
     AND [Target].col2 = [Source].col2 
     AND [Target].col3 = [Source].col3 
     AND [Target].col4 = [Source].col4 
     ) 
    WHEN NOT MATCHED BY TARGET 
    THEN INSERT (col1,col2,col3,col4,col5) 
    VALUES (
       [Source].col1 
       ,[Source].col2 
       ,[Source].col3 
       ,[Source].col4 
       ,[Source].col5 
       ) 
    WHEN MATCHED 
    THEN UPDATE SET [Target].col5 = [Source].col5; 
+0

这是否解决了这个问题,或者这只是原始的重构?如果使用select语句作为源,并且它不匹配任何记录,则合并将导致没有插入任何内容并且没有错误消息。所以在你原来的问题中,如果你把这个源的select语句直接运行,它应该不返回任何行。 –

相关问题