【问题标题】:c# ADO set context_info for SQL INSERT TRIGGERc# ADO 为 SQL INSERT TRIGGER 设置 context_info
【发布时间】:2018-06-07 07:25:40
【问题描述】:

我必须使用现有的使用 CONTEXT_INFO 的 INSERT 触发器...

如何将“context_info”传递给 c# SqlCommand 以使该触发器继续正常工作?

在 SQL 触发器中的使用:

select @ctxt=context_info from master.dbo.sysprocesses where spid = @@spid
set @session=substring(@ctxt,1,4)
set @contextid=substring(@ctxt,5,4)
set @ntduser=substring(@ctxt,9,120)

试过了:

                            //string strContext = "declare @context_info varbinary(30) set @context_info = cast('abcdefghijklmnopqrstuv1234567890' as varbinary(30)) set context_info @context_info";
                            ///////////////

                            SqlCommandBuilder cb = new SqlCommandBuilder(da);
                            da.UpdateCommand = cb.GetUpdateCommand();
                            //da.UpdateCommand.CommandText= da.UpdateCommand.CommandText.Replace(" WHERE ", strContext+" WHERE ");
                            //da.UpdateCommand.CommandText = "SET CONTEXT_INFO  0x1 " + da.UpdateCommand.CommandText;
                            da.Update(dataTable);
                            da.Dispose();

查看注释掉的代码... 在我的 SQL 触发器中,“context_info”总是空的

已经读过: https://social.msdn.microsoft.com/Forums/en-US/4a0ecb28-11cb-45ec-adbd-d72ac65b158a/how-to-pass-net-applications-parameter-to-a-trigger?forum=transactsql 但也不起作用。

没有将 context_info 传递给 SqlCommand 或 SqlConnection 或 SqlTransaction 的示例吗?

【问题讨论】:

  • 我并没有真正遵循您在这里尝试做的事情。除了修改和使用UpdateCommand,您能向我们展示它最终是什么吗?
  • 查看我的触发器中的代码示例。如何传递“context_info”?
  • 您正在执行查询,而不是触发器。如果您有如此复杂的逻辑(为什么?)编写存储过程而不是尝试连接字符串。但是,您首先要做什么?如果要传递用户和会话信息,请明确执行。不要试图依赖魔术字符串和全局变量
  • 无法更改触发器,因为它不是我的。我已经使用了现有的,这需要 context_info 登录...
  • 将此信息添加到问题中...

标签: c# sql ado.net ado sqlcommand


【解决方案1】:

我曾经使用过这样的东西(简化)来设置一些信息(guid),以便可以从触发器内部检索它......

string sql = $"DECLARE @session uniqueidentifier; SET @session = '{guid}'; SET CONTEXT_INFO @session";
var cmd = new SqlCommand(sql, connection, transaction);
cmd.ExecuteNonQuery();

请务必不要关闭设置 context_info 和调用触发器之间的连接...

【讨论】:

  • 我在我的 INSERT 命令之前发送它并且它有效。如我在问题中发布的链接中所述。不过,感谢您的帮助...
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2011-03-16
  • 2014-08-01
  • 1970-01-01
  • 2022-06-11
  • 2011-09-18
  • 1970-01-01
  • 2012-07-04
相关资源
最近更新 更多