Solved

Help in writing trigger

Posted on 2014-03-20
4
397 Views
Last Modified: 2014-04-03
Hi I have two tables.

Table1
Client_ID int Identity    (PK)

ClientName Varchar(50)
gender Bit
Address varchar(300)
Status char(1)

and a Log table

Table_History

History_ID int Identity(1,1) (PK)

User_ID   int
FieldEffected varchar
Olddata varchar
newdata varchar
timestamp datetime

can any one help me in writing trigger for Insert , Update and delete . for timebeing I can fix user_ID as '1000001'
0
Comment
Question by:Vikash p
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
  • 2
4 Comments
 
LVL 32

Accepted Solution

by:
bhess1 earned 167 total points
ID: 39944035
In this case, you would do better with three triggers rather than only one.

On your AFTER INSERT trigger, you know every column was changed.  You have the option of logging each item into the table separately, or entering a special row where FieldEffected could equal INSERT, ALL (INSERT), or some other specific value you choose.  OldData would be NULL, and newData would be something like:

Cast(@@Identity as varchar(10) ) + '|' + IsNull(i.ClientName, '') + '|' + Cast(i.gender as char(1)) + '|' + ....  Until you have all of the fields appended into one string.  This is simple.  However, having one item per field is cleaner, so you may decide to simply explicitly code each separate insert into the trigger.  An almost identical procedure could be created for a AFTER DELETE trigger as well.

It only gets complex on an update trigger.

There are various ways that you could try to automate the trigger so that you would always include each field in the table.  Iterating through the correct system view would let you automatically generate the INSERT statements.  However, for this example, I am assuming fixed code for the query.

There are two primary ways to identify if a column has changed (three, if you count a direct compare between INSERTED and DELETED).  The simplest to understand is the UPDATE() function, e.g.

IF UPDATE(ClientName)
... add logging code here ...

IF UPDATE(Gender)
....

Note that the documentation indicates that UPDATE() will return TRUE even if the update failed (that is, nothing changed).

There is also the COLUMNS_UPDATED() function, that returns a bit pattern indicating which columns changed (if any). This returns a VARBINARY containing enough bits so that there is one bit per column in the table.  If you performed an UPDATE on the sample table snippet:


Client_ID int Identity    (PK)
ClientName Varchar(50)
gender Bit
Address varchar(300)
Status char(1)

You would get a bit pattern like:

000 -- There are only five fields, so the last three bits per byte are useless
0     -- Status not updated
1     -- address updated
0     -- gender not updated
1     -- Client Name updated
0     -- Normally, you will not be updating the ID

However you determine it, when you identify the changed columns, you then do a simple INSERT into your log with the appropriate data.
0
 
LVL 75

Assisted Solution

by:Anthony Perkins
Anthony Perkins earned 333 total points
ID: 39944050
You may want to rethink the design.  However if that is not an option then something like this should do it:
CREATE TRIGGER trg_YourTrigger ON Table1 
	AFTER INSERT, UPDATE, DELETE 

AS

BEGIN

IF UPDATE(ClientName)
	INSERT Table_History ([User_ID], FieldEffected, Olddata, newdata, [timestamp])
	SELECT  '1000001', 'ClientName', d.ClientName, i.ClientName, GETDATE()
	FROM	DELETED d
			FULL OUTER JOIN INSERTED i ON d.Client_ID = i.Client_ID
	WHERE	d.Client_ID IS NULL				-- INSERT
			OR i.Client_ID IS NULL			-- DELETE
			OR d.ClientName <> i.ClientName	-- UPDATE and the values changed

IF UPDATE(gender)
	INSERT Table_History ([User_ID], FieldEffected, Olddata, newdata, [timestamp])
	SELECT  '1000001', 'gender', d.gender, i.gender, GETDATE()
	FROM	DELETED d
			FULL OUTER JOIN INSERTED i ON d.Client_ID = i.Client_ID
	WHERE	d.Client_ID IS NULL				-- INSERT
			OR i.Client_ID IS NULL			-- DELETE
			OR d.gender <> i.gender			-- UPDATE and the values changed

IF UPDATE([Address])
	INSERT Table_History ([User_ID], FieldEffected, Olddata, newdata, [timestamp])
	SELECT  '1000001', 'Address', d.[Address], i.[Address], GETDATE()
	FROM	DELETED d
			FULL OUTER JOIN INSERTED i ON d.Client_ID = i.Client_ID
	WHERE	d.Client_ID IS NULL				-- INSERT
			OR i.Client_ID IS NULL			-- DELETE
			OR d.[Address] <> i.[Address]	-- UPDATE and the values changed

IF UPDATE([Status])
	INSERT Table_History ([User_ID], FieldEffected, Olddata, newdata, [timestamp])
	SELECT  '1000001', 'Status', d.[Status], i.[Status], GETDATE()
	FROM	DELETED d
			FULL OUTER JOIN INSERTED i ON d.Client_ID = i.Client_ID
	WHERE	d.Client_ID IS NULL				-- INSERT
			OR i.Client_ID IS NULL			-- DELETE
			OR d.[Status] <> i.[Status]		-- UPDATE and the values changed
END

Open in new window

0
 
LVL 75

Assisted Solution

by:Anthony Perkins
Anthony Perkins earned 333 total points
ID: 39944058
Note that the documentation indicates that UPDATE() will return TRUE even if the update failed (that is, nothing changed).
It will always be true if the column participated in an UPDATE statement, regardless of whether the value changed or not.  So really the only way to truly know if the value changed is to compare the values in Deleted and Inserted.
0
 
LVL 69

Expert Comment

by:Scott Pletcher
ID: 39945218
When you compare the old and new values, you also need to compare correctly to allow NULL value(s) to be on one side or the other or both.
0

Featured Post

Webinar: Aligning, Automating, Winning

Join Dan Russo, Senior Manager of Operations Intelligence, for an in-depth discussion on how Dealertrack, leading provider of integrated digital solutions for the automotive industry, transformed their DevOps processes to increase collaboration and move with greater velocity.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Use this article to create a batch file to backup a Microsoft SQL Server database to a Windows folder.  The folder can be on the local hard drive or on a network share.  This batch file will query the SQL server to get the current date & time and wi…
JSON is being used more and more, besides XML, and you surely wanted to parse the data out into SQL instead of doing it in some Javascript. The below function in SQL Server can do the job for you, returning a quick table with the parsed data.
Via a live example, show how to extract information from SQL Server on Database, Connection and Server properties
Viewers will learn how to use the SELECT statement in SQL to return specific rows and columns, with various degrees of sorting and limits in place.

732 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question