这是我要执行的代码:
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/