我有一个表,其中 2 列将根据其他几个表中记录的存在进行更新。此外,需要为此目的使用临时表。并且,最后需要对更改进行审计跟踪。我在正确的道路上吗?
我尝试了以下方法:
SELECT t1.ref_no, t1.closr_date, t1.ext_key INTO #temp100
FROM [dbo].[Table1] t1
WHERE
( t1.[CLOSR_DATE] IS NULL )
.....以及在同一张表中要满足的其他一些条件
SELECT ref_no INTO #temp200
FROM [dbo].[Table2] t2
INNER JOIN [dbo].[Table3] t3
ON t3.[RFVAL_NO] = t2.[SCT_NO] )
WHERE (( t2.[START_DTTM] > GETDATE() OR t2.[START_DTTM] IS NULL ) )
UNION ALL
SELECT ref_no FROM [dbo].[Table3] t4
WHERE ( [A_DTTM] > GETDATE() OR [A_DTTM] IS NULL )
UNION ALL
SELECT ref_no FROM [dbo].[Table5] t5
WHERE ( [AS_DTTM] > GETDATE() OR [AS_DTTM] IS NULL )
.....等等
/ **删除#temp100 中的所有记录(匹配#temp200 中的条目) ** /
DELETE FROM #temp100 WHERE EXISTS (SELECT NULL FROM #temp200 WHERE #temp200.ref_refno = #temp100.ref_refno);
PRINT 'Records from table t1 (that match records in table #temp100 have been deleted!)'
/ **更新 [dbo].[Table1] 中保留在表 #t100 中的记录 * * /
UPDATE [dbo].[Table1] t1
SET [dbo].[t1].[CLOSR_DATE] = CAST('01-JAN-2011' AS DATE), [dbo].[t1].[EXT_KEY] = 'some string'
WHERE [dbo].[t1].[CLOSR_DATE] IN ( SELECT ref_no FROM #temp100 INNER JOIN [dbo].[Table1] t1 ON #temp100.ref_no = t1.[REF_NO] )
PRINT 'Records in table Table1 have been updated!'