Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pass a variable into a trigger

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.

like image 931
Codesleuth Avatar asked Apr 15 '10 15:04

Codesleuth


People also ask

Can you pass parameters to a trigger?

Basically you cannot pass parameters to a Trigger because Triggers get fired automatically by the database engine, and you do not interact with them directly as they execute. Putting it in another way, Stored Procedures and Functions etc.

Can we pass parameter to trigger in Oracle?

A) Yes they can, we're talking about nested triggers.

Can I use CTE in trigger?

However, you can write a CTE inside a stored procedure or User Defined Functions (UDFs) or triggers or views. However, you cannot implement CTEs inside indexed views.

Can we use transaction in trigger?

Because the trigger will already be operating within the context of a transaction, the only transaction control statements you should ever consider using in a trigger are ROLLBACK and SAVE TRAN.


1 Answers

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 from context_info column in dbo.sysprocesses.

like image 50
gbn Avatar answered Oct 13 '22 12:10

gbn