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.
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.
A) Yes they can, we're talking about nested triggers.
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.
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.
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
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With