Wednesday, March 21, 2012

INSERT Trigger

I have to use an INSERT Trigger and I want to refer to the inserted row. Is there some keyword to get the inserted row or do I have to pick out the inserted rows by myself? Or even worse is there no possibility and do I have to make changes to the whole table? What I wanna do is if a value is null after insert, to set it 0.

tia

Greetings,
DoraThere is a virtual table called INSERTED. You can join to other tables, select the columns into variables, etc.|||Here's a sample of an insert trigger that does something similar to what you are asking for...
CREATE TRIGGER TrgIn_Areas
ON dbo.Areas FOR INSERT AS

DECLARE @.dDate DATETIME
DECLARE @.strName VARCHAR(30)

SELECT @.dDate = GETDATE()
SELECT @.strName = (SELECT nt_username
FROM master..sysprocesses
WHERE spid = (SELECT @.@.SPID))

UPDATEAreas
SET CreatedBy = @.strName,
CreatedDate = @.dDate
FROM inserted
WHEREAreas.AreaID = inserted.AreaID

No comments:

Post a Comment