合并更新查询无法正常执行的问题

时间:2017-01-03 04:10:16

标签: sql sql-server version-control merge sql-update

我正在尝试在sql server中执行合并更新查询。

表" my_table"有4列"字段" (字符),"日期"(日期)," VAL"(数字),"修订"(日期时间)

查询是这样的:

MERGE "my_table" AS Target USING ( VALUES ('field_example','2017-01-04','0','2017-01-03 12:02:02')) AS Source ("field","date","val","revision")
                   ON (Target."field" = Source."field" AND Target."date" = Source."date")
                   WHEN MATCHED 
                   THEN UPDATE SET Target."val" = Source."val",Target."revision" = Source."revision"
                   WHEN NOT MATCHED BY TARGET 
                   THEN INSERT ("field","date","val","revision")
                   VALUES (Source."field", Source."date", Source."val", Source."revision")
                   OUTPUT $action, Inserted.*, Deleted.*; 

因为" my_table" with field =" field_example"和日期=' 2017-01-04',我希望此查询更新其他2列" val"," revision"。

我得到以下查询输出:

$action            field       date            revision val          field.1     date.1          revision.1  val.1
1  UPDATE field_example 2017-01-04 2017-01-03 12:02:02   0 field_example 2017-01-04 2017-01-03 10:09:25 161250

所以它看起来不错(应该更新)

但是当我查看数据库时,该行还没有更新(= val仍然是161250而不是0,修订版仍然是2017-01-03 10:09:25)

知道为什么吗?

1 个答案:

答案 0 :(得分:7)

  

然而,当我查看数据库时,该行尚未更新(=   val仍然是161250而不是0,修订仍然是2017-01-03   10时09分25秒)

     

知道为什么吗?

也许您正在查询不同的表/数据库或者事务已回滚。下面的脚本按预期工作,猜测实际的数据类型。

CREATE TABLE dbo.my_table(
     "field" varchar(100)
     ,"date" date
     ,"val" int
     ,"revision" datetime
     );

INSERT INTO my_table ("field","date","val","revision")
    VALUES ('field_example','2017-01-04','161250','2017-01-03 10:09:25');

MERGE "my_table" AS Target USING ( VALUES ('field_example','2017-01-04','0','2017-01-03 12:02:02')) AS Source ("field","date","val","revision")
    ON (Target."field" = Source."field" AND Target."date" = Source."date")
    WHEN MATCHED THEN
        UPDATE SET Target."val" = Source."val",Target."revision" = Source."revision"
    WHEN NOT MATCHED BY TARGET THEN
        INSERT ("field","date","val","revision")
            VALUES (Source."field", Source."date", Source."val", Source."revision")
    OUTPUT $action, Inserted.*, Deleted.*; 

SELECT "field","date","val","revision" 
FROM my_table;