Link to home
Start Free TrialLog in
Avatar of Vikash p
Vikash p

asked on

foreach loop in sql server trigger

Hi ,

I have a table with 50 columns . I need to store insert ,update log in audit table.

for that i am writing triggers.

insert into HC_Audit
           (User_ID,System_Time,Affected_Table,Affected_Field,Old_Data,New_Data)
      values(@user_id,@InsertDate,'Care','Emp_ID','',@Emp_id);


can anyone help me to run for each loop to get column name and column value so that i can insert data into hc_Audit table from insert , update , delete trigger .
Avatar of lcohan
lcohan
Flag of Canada image

For INSERT you just:

SELECT * FROM INSERTED or even better:

insert into HC_Audit
           (User_ID,System_Time,Affected_Table,Affected_Field,Old_Data,New_Data)
SELECT User_ID,System_Time,Affected_Table,Affected_Field,Old_Data,New_Data FROM INSERTED

assuming the tables have identical structure.


For DELETE is the same just replace INSERTED with DELETED - these are internal SQL tables used during the standard DML operations.

For UPDATE is a bit more tricky as an UPDATE is done in SQL like a INSERT and DELETE so the INSERTED table in a update trigger will have all NEW values going in that row(s) and the DELETED table will have all the OLD values that were updated by the new values coming from INSERTED.

Based on this you can chose to log both operations  and keep old/new values for an update.

I also suggest in your Audit table to add a TriggerAction column for instance to be able to tell what operation was logged - Insert/Delete/Update or...you can have one table for each of them but that would mean three audit tables for 1 parent.

"Using the inserted and deleted Tables"
http://technet.microsoft.com/en-us/library/ms191300(v=sql.100).aspx

http://www.mssqltips.com/sqlservertip/2342/understanding-sql-server-inserted-and-deleted-tables-for-dml-triggers/
Avatar of Vikash p
Vikash p

ASKER

I have 50 columns in a table can any one give me code to use foreach loop in sql server in which i can get coulumn name and value ..
ASKER CERTIFIED SOLUTION
Avatar of David Todd
David Todd
Flag of New Zealand image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
SOLUTION
Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial