Pass a parameter to a SQL Server trigger

brccelvz  于 2023-05-05  发布在  SQL Server
关注(0)|答案(3)|浏览(141)

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?

oalqel3c

oalqel3c1#

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
g2ieeal7

g2ieeal72#

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 .

laximzn5

laximzn53#

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.

相关问题