MERGE is inserting NULL records also
我使用以下语句来更新/插入记录。 问题是我已经给出条件
Cannot insert the value NULL into column 'Name', table 'TEST2'; column does not allow nulls. UPDATE fails.
那是因为TARGET表中的Name列有一个
1 2 3 4 5 6 7 8 9 10 11 12 13 | MERGE TEST2 AS TARGET USING TEST1 AS SOURCE ON TARGET.ID = SOURCE.ID AND SOURCE.Name IS NOT NULL WHEN MATCHED THEN UPDATE SET ID=SOURCE.ID, Name= SOURCE.Name, City= SOURCE.City, State = SOURCE.State WHEN NOT MATCHED THEN INSERT (ID, Name, City, State) VALUES(SOURCE.ID, SOURCE.Name, SOURCE.City, SOURCE.State); |
如果
可以将这些附加谓词添加到各个分支。 例如。
1 | WHEN NOT MATCHED AND SOURCE.Name IS NOT NULL |
但是因为你没有
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 | MERGE TEST2 AS TARGET USING (SELECT * FROM TEST1 WHERE Name IS NOT NULL) AS SOURCE ON TARGET.ID = SOURCE.ID WHEN MATCHED THEN UPDATE SET ID = SOURCE.ID, Name = SOURCE.Name, City = SOURCE.City, State = SOURCE.State WHEN NOT MATCHED THEN INSERT (ID, Name, City, State) VALUES(SOURCE.ID, SOURCE.Name, SOURCE.City, SOURCE.State); |
您只需在WHEN NOT MATCHED中添加AND条件,如下所示:
1 2 3 4 5 6 7 8 9 10 11 12 13 | MERGE TEST2 AS TARGET USING TEST1 AS SOURCE ON TARGET.ID = SOURCE.ID AND SOURCE.Name IS NOT NULL WHEN MATCHED THEN UPDATE SET ID=SOURCE.ID, Name= SOURCE.Name, City= SOURCE.City, State = SOURCE.State WHEN NOT MATCHED AND SOURCE.Name IS NOT NULL THEN INSERT (ID, Name, City, State) VALUES(SOURCE.ID, SOURCE.Name, SOURCE.City, SOURCE.State); |