C# 内有声明变量的T-SQL参数化查询?
以下是我试图执行的代码:C# 内有声明变量的T-SQL参数化查询?,c#,.net,tsql,ado.net,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(GE
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
-这就是为什么我将查找分解并插入到两个查询中的原因您不能将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语句封装到一个存储过程中,您可以使用参数调用该存储过程,并让该过程处理您可能需要的所有额外步骤….您是否尝试将@AccountKey作为sqlparmaeter,但将其方向更改为输出?这样,您仍然可以根据对marc_答案的反馈选择一个值,您可以使sql看起来像这样
INSERT dbo.CREException (CreatedOn, Message, Source, StackTrace, AccountKey, Category, Priority)
VALUES(GETUTCDATE(), @Message, @Source, @StackTrace
,(SELECT AccountKey FROM dbo.CREAccount WHERE AccountId = @AccountId)
, @Category, @Priority)
如果您想要account key的默认值,那么合并结果就很容易了,这就是我要键入的:)我不想要SP,是的,像我这样做的关键是因为AccountKey可以为NULL,所以SQL不会插入任何内容。我的想法与此一模一样,但新的要求是允许AccountKeys中使用null。我希望在脚本中如何使用参数和参数能找到答案:)@katit:我看到的唯一两种解决方案是:(1)使用存储过程(不清楚为什么你这么反对它——这会解决你的问题!),或者(2)确定T-SQL外部的
AccountKey
值,并将其作为附加参数传入。我认为没有其他办法解决这个问题。你挑吧……事实上我成功了。使用SELECT MIN(AccountKey)并在需要时生成NULL。您得到的错误到底是什么?我看不出你的SQL查询有任何不起作用的原因,我一直在使用这种技术。这应该是公认的答案。添加@AccountKey作为参数。cmd.Parameters.Add(“@AccountKey”,SqlDbType.BigInt).Direction=ParameterDirection.Output;然后删除查询字符串中的声明。行了。