Please start any new threads on our new
site at https://forums.sqlteam.com. We've got lots of great SQL Server
experts to answer whatever question you can come up with.
| Author |
Topic |
|
AskSQLTeam
Ask SQLTeam Question
0 Posts |
Posted - 2006-04-11 : 09:27:27
|
| Russell writes "Alter TRIGGER trgContactLogTrig ON tblContact FOR UPDATE AS DECLARE @Columns VARCHAR(200)DECLARE @Count INTEGERDECLARE @ColCount INTEGERDECLARE @SQLSTR AS VARCHAR(8000)DECLARE @Byte INTEGERDECLARE @Bit INTEGERDECLARE @Test INTEGERDECLARE @strInserted AS VARCHAR(50)DECLARE @strDeleted AS VARCHAR(30)DECLARE @strIns AS VARCHAR(30)DECLARE @field intDECLARE @maxfield intDECLARE @EXECSQLSTRING nvarchar (4000)SET @maxfield = (( SELECT COUNT(*) FROM information_schema.columns where table_name = 'tblContact' ) + 1) SET @field = 1/* SELECT @field = 1, @maxfield = max(ORDINAL_POSITION) FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME = 'tblContact' */SELECT @ColCount = (@maxfield - 1) -- gives the number of columns SELECT @Byte = ((@ColCount - 1) / 8) + 1SELECT @Bit = (@ColCount - 1) % 8 + 1SELECT @Bit = power (2,@Bit -1)SET @SQLSTR = 'Changes are : 'SET @strInserted = ''WHILE @field < @maxfield/* IF (Substring(COLUMNS_UPDATED() , @Byte, 1) = power(2, @Bit-1 )) */ /* IF substring(COLUMNS_UPDATED(),@Byte, 1) & @Bit > 0 */BEGIN SET @Columns = ( SELECT COLUMN_NAME FROM information_schema.columns where table_name='tblContact' and ORDINAL_POSITION = @field ) set @EXECSQLSTRING = 'SELECT ' + @Columns + ' from inserted' EXEC (@EXECSQLSTRING)--SET @strDeleted = (SELECT @Columns from deleted) -- previous value--SET @strInserted = (SELECT @Columns from inserted) -- current valueSET @SQLSTR = @SQLSTR + ' | ' + @Columns + '(' + @strDeleted + ',' + @strInserted + ')' SET @field = @field + 1 ENDINSERT INTO tblContactLog VALUES ( 1 , @strInserted , @Bit , 'test', @SQLSTR ) GOHi all,I'm writing the above trigger to audit a table. I wan the trigger to write information of the changed columns only. So far I have got stuck in two places purely because I lack knowledge in SQL Triggers.The two areas are the columns updated function and executing a dynamic sql statement to return a value to an variable. Can some one please tell me how to use the columns updated so I could track which column has changed and also how to write a dynamic select statement on the inserted table and get a value out to a variable.Thank you allRussell" |
|
|
robvolk
Most Valuable Yak
15732 Posts |
|
|
|
|
|
|
|