Simple T-SQL Trigger question

Bulldog13

Golden Member
Jul 18, 2002
1,655
1
81
I have a table, TABLE_A.

TABLE_A has 3 fields. PK (auto, identity), Name(varchar(50)), and Date_Created (datetime).

When I insert a row into TABLE_A, PK is automatically generated. Name is passed in via a variable in a stored procedure (basic insert statement).

I would like a trigger to automatically fill in the current date time into the Date_Created field.

Here is what I have so far:

CREATE TRIGGER INSERT_TABLE_A

on TABLE_A

for INSERT AS

DECLARE
@NOW DateTime
set @NOW = getdate()


This is where I get confused....how do I insert the current date time into the newly created record?

Thanks in advance

 

GilletteCat

Member
Dec 28, 2001
181
0
0
You can, of course, do this with a trigger, and it's not difficult at all. But you should use the Default value feature and set Date_Created column's default value to be getdate().
 

Bulldog13

Golden Member
Jul 18, 2002
1,655
1
81
Originally posted by: GilletteCat
You can, of course, do this with a trigger, and it's not difficult at all. But you should use the Default value feature and set Date_Created column's default value to be getdate().

Thanks for the heads up. I will implement it in this manner the next time I have to do something like this.

Anyways, I found the answer to my original question here...

http://forums.devx.com/archive/index.php/t-25030.html
 

GilletteCat

Member
Dec 28, 2001
181
0
0
If you are adamant about the trigger, it would not actually be an insert, but rather, an update:
CREATE TRIGGER INSERT_TABLE_A

on TABLE_A

for INSERT AS

UPDATE TABLE_A SET Date_Created = getdate() where PK IN (SELECT PK FROM inserted)