I want to pass a parameter from a Session value in C# to my Trigger in SQL Server. Is it possible for me to do that?
-
1No, it is not possible. – juergen d Feb 21 '18 at 06:08
-
What exactly do you mean by pass it to a sql trigger? What are you trying to do? – cost Feb 21 '18 at 06:11
-
i am creating an audit trail and I want to pass the username of the logged in user to a parameter and insert it to my audit table – Adolf Bernard Moncawe Feb 21 '18 at 06:49
3 Answers
A trigger can't accept parameters, Instead, you can use a function or stored procedure. Or if you want the trigger to work based on some parameters or values from your session, try this
- Add a column to your table which will store the value from the session
- Now insert or update the value from your session to this new columns
- You can read the value inside the trigger from this column and do your calculations accordingly

- 732,580
- 175
- 1,330
- 1,459

- 7,826
- 3
- 22
- 39
Please and always mention the specific version and edition of sql server you are using. Functionality varies according to these facts; you can avoid a lot of misdirection and confusion by including that information.
Next, provide context for your questions. Does your application/architecture use a common login/user to access the database? If not, try user_name or one of the related functions. If it does use a common identity, then you will need to provide that information prior to executing the statement that fires the trigger. In older versions you use context_info; newer ones can use session_context.

- 2,830
- 4
- 11
- 14
I know I am a little late, but had the same kind of problem last week. I used the answer from this question:
How to add custom attributes to SQL connection string?
aka, used the ApplicationName attribute in c# and used the APP_NAME() in sql, as we did not use this variabel anywhere.
Your question, however seems like you could use the ORIGINAL_LOGIN() in sql, if it is an SQL user you want to save.
You could also, if you need the APP_NAME somewhere else, go with substringing the APP_NAME so that the first 100 bytes are for the application name and the rest is for a user. It is dirty and requires some manual labor but will do the job.

- 3
- 3