3

这是我正在尝试执行的代码:

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 个查询的原因

4

3 回答 3

3

难道你不能把你的 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 

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

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

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

于 2012-06-02T21:41:04.663 回答
1

您是否尝试将 @AccountKey 作为 sqlparmae​​ter 包含在内,但将其方向更改为输出?这样,您仍然应该能够在其中选择一个值

于 2012-06-02T22:03:53.977 回答
1

根据对 marc_s 答案的反馈,您总是可以让您的 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)

如果您想要帐户密钥的默认值,则很容易合并结果

于 2012-06-02T22:49:09.943 回答