简体   繁体   中英

SQL - updating records and keeping an audit trail of the changes

I have a table in which 2 columns are to be updated based on the existence of records in several other tables. Also, need to use temporary table for this purpose. And, finally am required to keep an audit trail of the changes. Am I on the right path here?

I have tried the following approach:

SELECT t1.ref_no, t1.closr_date, t1.ext_key INTO #temp100

FROM [dbo].[Table1] t1
WHERE 
 ( t1.[CLOSR_DATE] IS NULL )

.....and some other conditions to fulfil in the same table

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 )

.....and so on

/ ** Deleting all the records from #temp100 (that match entries in #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!)'

/ ** Updating records in [dbo].[Table1] that remain in table #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!'

You should use triggers for this task, it'll save you lots of coding. Try this Adding simple trigger-based auditing to your SQL Server database

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM