这是我正在尝试执行的代码:
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 个查询的原因