Click here to Skip to main content
15,881,882 members
Articles / Programming Languages / SQL

Detect Changes To A Database Table

Rate me:
Please Sign up or sign in to vote.
2.63/5 (21 votes)
25 Feb 20044 min read 89.8K   811   40  
This article sorts to illustrate one of the ways by which data table changes can be detected through the use of available aggregate functions like BINARY_CHECKSUM and CHECKSUM_AGG.
/* Step 1: Use the Northwind Database*/

USE NORTHWIND
GO

/* Step 2: Check if the Table TBLBINCHECK exists. If so, drop it. */

-- Check if the Table TBLBINCHECK exists
IF EXISTS (SELECT * FROM DBO.SYSOBJECTS WHERE ID = OBJECT_ID(N'TBLBINCHECK') AND OBJECTPROPERTY(ID, N'ISUSERTABLE') = 1)
-- Drop it if, it exist already
DROP TABLE TBLBINCHECK
GO 

/* Step 3: Create the Table TBLBINCHECK to hold the checksum value before the values in the specific rows i.e. SHIPPERID = 1 and 2 are changed. 
Note: Ensure there are rows in the SHIPPERS Table with SHIPPERID values 1 and 2. If not, insert them.*/

CREATE   TABLE TBLBINCHECK (SHIPPERID INT, BCHECKSUM INT)
INSERT   INTO TBLBINCHECK
         SELECT   SHIPPERID, BINARY_CHECKSUM(*)
         FROM      SHIPPERS

/* Step 4: Modify the values of the COMPANYNAME field in the SHIPPERS table for the rows with SHIPPERID field values 1 and 2.*/

UPDATE SHIPPERS SET COMPANYNAME = 'United Couriers' WHERE SHIPPERID = 1
UPDATE SHIPPERS SET COMPANYNAME = 'DHL', PHONE = '2345673' WHERE SHIPPERID = 2

/* Step 5: Determine which rows of the SHIPPERS table have been modified. 
Obtain the corresponding values of the SHIPPERID field. These values can be used as needed, say, for auditing purposes. */   SELECT 
 	SHIPPERID FROM
	TBLBINCHECK   WHERE   EXISTS
	(SELECT
		SHIPPERID      FROM
		SHIPPERS       WHERE SHIPPERS.SHIPPERID =
		TBLBINCHECK.SHIPPERID   AND BINARY_CHECKSUM(*) <> TBLBINCHECK.BCHECKSUM)

By viewing downloads associated with this article you agree to the Terms of Service and the article's licence.

If a file you wish to view isn't highlighted, and is a text file (not binary), please let us know and we'll add colourisation support for it.

License

This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here


Written By
Web Developer
India India
MCSD in .NET,
WIPRO TECHNOLOGIES,
BANGALORE, INDIA

Comments and Discussions