When I try to create this trigger, I get this exception:
The name "SITE_ID" is not permitted in this context. Valid expressions are constants, constant expressions, and (in some contexts) variables. Column names are not permitted.
CREATE TRIGGER tr_VISITACTIVITY_insert ON VISITACTIVITY
INSTEAD OF INSERT AS
BEGIN
INSERT INTO [VISITACTIVITY]
([O_ID]
,[SITE_ID]
,[VISIT_DATE]
,[STAFF]
,[VISIT_TYPE_ID]
,[COMMENTS]
,[DELETED])
VALUES
(-1
,SITE_ID
,VISIT_DATE
,STAFF
,VISIT_TYPE_ID
,VISIT_COMMENTS
,0
)
GO
END
GO
The insert that the programmer would issue in the application is something like this:
INSERT INTO [VISITACTIVITY]
([SITE_ID]
,[VISIT_DATE]
,[STAFF_COMMENT]
,[VISIT_TYPE_ID]
,[COMMENTS]
)
VALUES
(15
,'2011-08-08'
,'Eric, John'
,6
,'invasives growing along the border of the preserve'
)
So, I need the values that the programmer provided in the insert to create the insert in the trigger.
How to I reference these values, then, in the trigger?
Thanks.
You need to look at the meta-table
INSERTED, which is basically a table that contains all the data being inserted, so you’d reference (for example)SITE_IDasinserted.SITE_ID.What you also need to be careful of as well is doing single-row inserts from within the trigger (as you seem to be doing). If multiple rows are inserted in a batch, then
INSERTEDwill contain multiple rows. So what you need to do is to useINSERT INTO table (...) SELECT ..., for example:By the way, reading your question, it looks like you’re just using the trigger to populate default values in a couple of columns. Have you considered just using a DEFAULT constraint on the table instead? For example, if you did the following:
…then this would make your example insert behave in the same way without the trigger. It depends whether you always want to override the values in Deleted or O_ID or not. If you always want to override, use a trigger – or better yet, stick a
CHECKon the column to force it to a fixed value (will also highlight where your code is trying to change it as SQL Server will fail the insert due to referential integrity). If you want to be able to override it, then useDEFAULTconstraints.(Of course, you may well have simplified the problem for the sake of the question, but I’m just highlighting how you can do this without resorting to a trigger).