Can I pass arguments to an external (CLR) SQL Server trigger?

戏子无情 提交于 2020-01-03 03:19:05

问题


I have a trigger in SQL Server, but I need to pass arguments to the CLR code, i.e., information not provided in the trigger context.

Is something like this even possible?

CREATE TRIGGER MyTrigger ON MyTable FOR INSERT
AS EXTERNAL NAME MyAssembly.MyNamespace.MyTriggerHandler("Foo", "Bar")

These arguments would be static, of course.

The number of argument permutations is discrete, but creating a separate class or function in the CLR assembly for each would be unwieldy, and would require a compile / deploy step I want to avoid every time another trigger is needed.


回答1:


After a little research, it appears what I want to do, can't be done.

Methods passed using the trigger "external name" clause must be parameterless, and the SqlTriggerContext cannot be modified in the CREATE TRIGGER statement.

I ended up going the permutation route and just having fewer variations of supported arguments. Perhaps .NET integration will be a little more robust next time around.




回答2:


In a sense you can pass information to a Trigger (whether T-SQL or SQLCLR), just not directly as you are showing in the question. Still, you have 2 or 3 options for passing information that is not part of the DML operation itself to any Triggers in chain of events:

  1. Local temporary table
  2. SET CONTEXT_INFO / CONTEXT_INFO
  3. On SQL Server 2016 or newer: sp_set_session_context / SESSION_CONTEXT

In all cases you would get the values by executing a SqlCommand (use "Context Connection = true;" as the connection string) with an output SqlParameter to pull the value into the .NET code.




回答3:


yeah you can use the sp_OA procedures for this: http://msdn.microsoft.com/en-us/library/aa238863(SQL.80).aspx



来源:https://stackoverflow.com/questions/1128386/can-i-pass-arguments-to-an-external-clr-sql-server-trigger

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!