SQL - 更新记录并保留更改的审计跟踪

时间:2012-09-02 22:44:28

标签: sql sql-server temp-tables updates

我有一个表,根据其他几个表中记录的存在,要更新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]。[表1]中保留在表#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!'

1 个答案:

答案 0 :(得分:0)

您应该使用触发器执行此任务,它将为您节省大量编码。试试这个Adding simple trigger-based auditing to your SQL Server database