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 

まだすべてのパラメーターがあり、例のようにテーブルAccountKeyからの値を決定しています。dbo.CREAccount

AccountKeyテーブルに値が見つからない場合に備えて、「デフォルト」値を提供することを考える必要があるかもしれません...

または、何らかの理由でそれが機能しない場合は、これらの 2 つまたは 3 つの 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 に答える