Here is my code I’m trying to execute:
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();
}
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? accountId parameter can be null – thats why I break down lookup and insert into 2 queries
Couldn’t you just rewrite your T-SQL to be:
You still have all your parameters, and you’re determining the value for
AccountKeyfrom thedbo.CREAccounttable as in your example.Maybe you need to think about providing a “default” value for
AccountKeyin case no value is found in the table…Or if that doesn’t work for some reason, then I’d probably just wrap up these two or three T-SQL statements into a stored procedure which you can call with the parameters and let that procedure handle all the extra steps you might need….