Dynamically retrieve composite primary key values in trigger

时间:2015-11-12 11:41:22

标签: tsql triggers sql-server-2014

I have database with around 100 tables and I need to implement log of actions like insert, update and delete on all those tables.

I decide to use a trigger as logging mechanism, and problem I have is to dynamically get values of columns that forms primary keys (some primary key are identity, and some are composite keys made of two columns).

I know this can be done via dynamic SQL, but I am asking myself, and now even you, is it possible to somehow avoid dynamic SQL in trigger definition.

So, my log table looks like:

CREATE TABLE [dbo].[HistoryTable](
    [HistoryTable] [int] IDENTITY(1,1) NOT NULL,
    [PKValues] [varchar](50) NOT NULL,
    [AllValues] [nvarchar](500) NOT NULL,
)

So, if table consists composite primary key, then values of those columns affected by insert, update or delete action must be one value with values separated with comma, or semi-colon:

PKValues    AllValues

1;1         <row columnId1=1 columnId2=1 Title="test" />
1;2         <row columnId1=1 columnId2=2 Title="test2" />
1           <row columnId1=1 Title="test3" />
...

First two rows in example are from table with composite primary key, and third row is from table with single identity column as primary key.

0 个答案:

没有答案