如何更新插入选择查询中的记录

时间:2020-04-11 15:32:14

标签: sql-server

我有这个查询,我正在通过选择查询在表中插入日期。

INSERT INTO TEST
SELECT * FROM (SELECT myDate, EmpCode, '2020-04-11 09:10:21', '2020-04-11 18:47:56') TBL
WHERE NOT EXISTS (SELECT * FROM TEST WHERE myDate = TBL.myDate AND EmpCode = TBL.EmpCode)

此查询可能生成的日期为

Date          EmpCode  Check In               Check Out
2020-04-11    101      2020-04-11 09:10:21    2020-04-11 18:47:56

因此,如果我尝试添加相同的记录,它将不会添加到TEST表中,但是如果我更改值,它将被添加。假设EmpCode是101,而myDateGETDATE()。现在,对于同一日期和同一员工,如果我更改任何列的值,那么这里的第一个datetimeCheck In,第二个是Check Out,所以如果我将Check Out更新为{{1 }},我不想在表中插入任何行,而是用新值更新现有行。我应该做些什么来使这项工作。用更新后的值执行查询后的输出应该是

'2020-04-11 18:19:32'

1 个答案:

答案 0 :(得分:0)

我认为您正在寻找MERGE声明。

MERGE TEST AS TARGET
    USING (SELECT myDate, EmpCode, '2020-04-11 09:10:21' AS check_in, '2020-04-11 18:47:56' AS check_out) AS SOURCE
-- Replace it with with actual source query. this is just an exmaple.
ON TARGET.EmpCode = SOURCE.EmpCode
AND TARGET.myDate = SOURCE.myDate
WHEN MATCHED
    THEN UPDATE SET 
        check_in = SOURCE.check_in
        , check_out = SOURCE.check_out
WHEN NOT MATCHED BY TARGET 
    THEN INSERT (myDate, EmpCode, check_in, check_out)
         VALUES (SOURCE.myDate, SOURCE.EmpCode, SOURCE.check_in, SOURCE.check_out);

您可以从hereofficial doc探索有关MERGE的更多信息。