简体   繁体   English

T-SQL MERGE语句未插入新记录-我的代码有什么问题?

[英]T-SQL MERGE statement is not inserting a new record - what is wrong with my code?

The code below is successfully updating an existing record but does not insert the new record where the details do not match and I don't understand why not as the code compiles and does not throw any error messages. 下面的代码可以成功更新现有记录,但是不会在细节不匹配的地方插入新记录,而且由于代码会编译并且不会引发任何错误消息,因此我不明白为什么不这样做。 I'm sure I have missed something obvious. 我敢肯定我错过了一些明显的事情。 For reference I using SQL Server 2008 with a case-sensitive collation but I don't see how that makes a difference. 作为参考,我将SQL Server 2008与区分大小写的排序规则一起使用,但是我看不出有什么区别。 I have other MERGE cases that work just fine, it's just this one that doesn't play nicely. 我还有其他的MERGE情况也很好,只是这种情况不能很好地发挥作用。

To see the update working, modify the colourid in the DEBUG variable declarations to be the same as the value in the insert statement. 要查看更新是否有效,请将DEBUG变量声明中的colourid修改为与insert语句中的值相同。

BEGIN TRY 
    DROP TABLE #adr_test
END TRY
BEGIN CATCH
    -- nothing to drop
END CATCH

CREATE TABLE #adr_test
(
    style NVARCHAR(5)
    ,size_id INT
    ,colour_id INT
    ,cost MONEY
)

INSERT INTO #adr_test (style, size_id, colour_id, cost) 
VALUES ('ADR01', 100, 101, 99.99)

/*DEBUG*/
DECLARE @style NVARCHAR(5) = 'ADR01'
DECLARE @sizeid INT = 100
DECLARE @colourid INT = 999
DECLARE @ctncost MONEY = 1.50
/*END DEBUG*/

MERGE #adr_test AS Tgt
USING (SELECT style, size_id, colour_id, cost
       FROM #adr_test                           
       WHERE style = @style
         AND size_id = @sizeid
         AND colour_id = @colourid) AS Src ON Src.style = Tgt.style
                                           AND Src.size_id = Tgt.size_id
                                           AND Src.colour_id = Tgt.colour_id

WHEN MATCHED AND Tgt.cost <> @ctncost 
   THEN
      UPDATE SET Tgt.cost = @ctncost

WHEN NOT MATCHED BY TARGET 
   THEN 
      INSERT (style, size_id, colour_id, cost)
      VALUES (@style, @sizeid, @colourid, @ctncost);


SELECT * FROM #adr_test

To elaborate on RBarry Young and Code Different's responses, NOT MATCHED compares what is in the SOURCE with what is in the target. 为了详细说明RBarry Young和Code Different的响应,未匹配将源中的内容与目标中的内容进行了比较。 Because I am selecting from the same table with the filter criteria, the source results are NULL so there is nothing to be NOT MATCHED. 因为我从具有过滤条件的同一张表中进行选择,所以源结果为NULL,因此没有任何内容不匹配。 the code in the USING should look like this 使用中的代码应如下所示

SELECT
    style = @style
    ,colour_id = @colourid
    ,size_id = @sizeid
    ,cost = @ctncost

This way the SOURCE will contain a results set with a single record which may or may not be found in the TARGET table. 这样,SOURCE将包含带有单个记录的结果集,该结果集可能在TARGET表中找到或找不到。 when it is not matched then the insert will be triggered. 如果不匹配,则会触发插入。

Thanks for your help guys. 感谢您的帮助。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM