I have a trigger
which deals with some data for logging purposes like so:
CREATE TRIGGER trgDataUpdated
ON tblData FOR UPDATE
AS
BEGIN
INSERT INTO tblLog ( ParentID, OldValue, NewValue, UserID )
SELECT deleted.ParentID, deleted.Value, inserted.Value,
@intUserID -- how can I pass this in?
FROM inserted INNER JOIN deleted ON inserted.ID = deleted.ID
END
How can I pass in the variable @intUserID
into the above trigger, as in the following code:
DECLARE @intUserID int
SET @intUserID = 10
UPDATE tblData
SET Value = @x
PS: I know I can't literally pass in @intUserID
to the trigger, it was just used for illustration purposes.
7条答案
按热度按时间bvjxkvbb1#
I use
SET CONTEXT_INFO
for this kind of action. That's a 2008+ link, prior link has been retired.On SQL Server 2005+, you'd have
CONTEXT_INFO
to read it but otherwise you have to get fromcontext_info
column indbo.sysprocesses
.cx6n0qe32#
you can't pass a variable into a trigger.
the only way to get the information in the trigger is to be able to SELECT it based on the INSERTED or DELETED tables or add a column onto the affected table and put the value in that column.
EDIT in the previous question OP posted about this, they said that they didn't want to use CONTEXT_INFO, but here they say it is Ok to use, so here is a CONTEXT_INFO usage example:
in the procedure doing the update
here is the portion of the trigger to retrieve the value:
tvz2xvvm3#
I use the sp_set_session_context stored procedure to set the value:
And in my trigger to read the value:
23c0lvtd4#
Old question, but I wonder how come nobody mentioned that temporary tables created before the trigger is invoked are visible in the trigger? So, this would work:
The trigger will see the temp table #intUserID and can read the id from there.
jaql4c8m5#
You cant pass variables to triggers. Depending on how users connect to the database you could use
SYSTEM_USER
to get the current user connected to the database.qzlgjiam6#
This is like a hack, but you can potentially pass in an APP name in the connection string, and your trigger will be able to access that value. When you compose the connection string, you can append the userid into the app name, and then in the trigger, you get the app name by calling
SET @AppName = APP_NAME();
and then parse out the userid from the @AppName Be warned that this approach will create tons of connection pools, not a good approach for web app.
tjvv9vkg7#
You do not pass variables to triggers because you are not able to call triggers directly. They are executed as a result of data being inserted, modified or deleted.