我有这个查询,我正在通过选择查询在表中插入日期。
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,而myDate
是GETDATE()
。现在,对于同一日期和同一员工,如果我更改任何列的值,那么这里的第一个datetime
是Check In
,第二个是Check Out
,所以如果我将Check Out更新为{{1 }},我不想在表中插入任何行,而是用新值更新现有行。我应该做些什么来使这项工作。用更新后的值执行查询后的输出应该是
'2020-04-11 18:19:32'
答案 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);
您可以从here或official doc探索有关MERGE
的更多信息。