?
Solved

Help in writing trigger

Posted on 2014-03-20
4
Medium Priority
?
413 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:
Brendt Hess earned 668 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 1332 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 1332 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

Get 15 Days FREE Full-Featured Trial

Benefit from a mission critical IT monitoring with Monitis Premium or get it FREE for your entry level monitoring needs.
-Over 200,000 users
-More than 300,000 websites monitored
-Used in 197 countries
-Recommended by 98% of users

Question has a verified solution.

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

Why is this different from all of the other step by step guides?  Because I make a living as a DBA and not as a writer and I lived through this experience. Defining the name: When I talk to people they say different names on this subject stuff l…
In this article we will get to know that how can we recover deleted data if it happens accidently. We really can recover deleted rows if we know the time when data is deleted by using the transaction log.
Via a live example, show how to extract information from SQL Server on Database, Connection and Server properties
Via a live example, show how to setup several different housekeeping processes for a SQL Server.
Suggested Courses

777 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