views:

49

answers:

3

I have a load of tables all with the same 2 datetime columns (lastModDate, dateAdded). I am wondering if I can set up global Insert Update trigger for these tables to set the datetime values. Or if not, what approaches are there?

Any pointers much appreciated

+1  A: 

No, there's no such thing as a "global" trigger or a multi-table triggers. Triggers are by design bound to a table, so if you need to have triggers on a load of tables, you need to create a load of triggers, one for each table, and deploy them. No way around that, I'm afraid.

marc_s
Thanks, kind of thought that but was just hoping. I could use a bit of convention over config here.
Chin
+1  A: 

You can use DEFAULT values for the inserts (dateAdded) and a TABLE trigger for the UPDATE.

Something like

CREATE TABLE MyTable (
        ID INT,
        Val VARCHAR(10),
        lastModDate DATETIME DEFAULT CURRENT_TIMESTAMP, 
        dateAdded DATETIME DEFAULT CURRENT_TIMESTAMP
)
GO

CREATE TRIGGER MyTableUpdate ON MyTable
FOR UPDATE
AS
UPDATE  MyTable
SET     lastModDate = CURRENT_TIMESTAMP
FROM    MyTable mt INNER JOIN
        inserted i ON mt.ID = i.ID
GO

INSERT INTO MyTable (ID, Val) SELECT 1, 'A'
GO

SELECT *
FROM MyTable
GO

UPDATE MyTable
SET Val = 'B' 
WHERE ID = 1
GO

SELECT *
FROM MyTable
GO

DROP TABLE MyTable
GO
astander
Thanks, that's what I was thinking. I will still need a update trigger for every table though right?
Chin
Yup, that would be the case...
astander
+2  A: 

I agree there is no such Global Trigger, but we can certainly reduce our efforts by creating script which will generate triggers for the tables.

Something like: http://weblogs.sqlteam.com/brettk/archive/2006/11/29/35816.aspx

Nitin Midha
That's very interesting. Thanks.
Chin