title: T-SQL Parameterized query with declared variable inside?
body: <p>Here is my code I'm trying to execute:</p>
  
  <pre><code>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 &gt; 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();
  }
  </code></pre>
  
  <p>As expected - it fails because @AccountKey is not specified in code - it is a parameter in T_SQL itself. How do I achieve what I want while using parameters? <code>accountId</code> parameter can be <code>null</code> - thats why I break down lookup and insert into 2 queries</p>