c# - 内部声明变量的 T-SQL 参数化查询?

标签 c# .net tsql ado.net

这是我要执行的代码:

const string Script = @"
DECLARE @AccountKey Int
SELECT @AccountKey = AccountKey FROM dbo.CREAccount WHERE AccountId = @AccountId 
INSERT dbo.CREException (CreatedOn, Message, Source, StackTrace, AccountKey, Category, Priority)
VALUES(GETUTCDATE(), @Message, @Source, @StackTrace, @AccountKey, @Category, @Priority)";

using (var command = new SqlCommand(Script, connection))
{
    var message = ex.Message;
    if (message.Length > 250) message = message.Substring(0, 250);

    command.Parameters.Add(new SqlParameter("@Message", message));
    command.Parameters.Add(new SqlParameter("@Source", ex.Source ?? string.Empty));
    command.Parameters.Add(new SqlParameter("@StackTrace", ex.StackTrace ?? string.Empty));
    command.Parameters.Add(new SqlParameter("@AccountId", accountId));
    command.Parameters.Add(new SqlParameter("@Category", category));
    command.Parameters.Add(new SqlParameter("@Priority", priority));

    command.ExecuteNonQuery();
}

正如预期的那样——它失败了,因为@AccountKey 没有在代码中指定——它是 T_SQL 本身的一个参数。使用参数时如何实现我想要的? accountId 参数可以是 null - 这就是我分解查找并插入到 2 个查询中的原因

最佳答案

您不能将您的 T-SQL 重写为:

INSERT INTO 
   dbo.CREException(CreatedOn, Message, Source, StackTrace, AccountKey, Category, Priority)
   SELECT       
      GETUTCDATE(), @Message, @Source, @StackTrace, 
      AccountKey, @Category, @Priority
   FROM 
      dbo.CREAccount 
   WHERE 
      AccountId = @AccountId 

您仍然拥有所有参数,并且您正在从 dbo.CREAccount 表中确定 AccountKey 的值,如您的示例所示。

也许您需要考虑为 AccountKey 提供一个“默认”值,以防在表中找不到任何值...

或者如果由于某种原因这不起作用,那么我可能只是将这两个或三个 T-SQL 语句包装到一个存储过程中,您可以使用参数调用它并让该过程处理所有额外的步骤你可能需要....

关于c# - 内部声明变量的 T-SQL 参数化查询?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10866127/

相关文章:

c# - 删除 1st Index 元素会导致表单不发布其他大于 1st 的索引

.net - 在VB.Net中遍历二维数组

c# - 如果文件不存在,试图让我的 SSIS 继续运行

C#类成员访问问题

c# - 我是否正确回答了这个面试挑战? (在 C# 中检查有效的二叉树)

c# - 系统.MissingMethodException : Method 'MvvmCross.Droid.Views.MvxAndroidViewPresenter..ctor' not found

c# - try catch 和 finally block 的执行顺序

xml - SQL Server XML 列存在()查询

sql - 确定列上使用的最大小数位数

sql - 有没有比 SQL 存储过程更好的方法?