2012-06-02 34 views
3

这里是我的代码,我试图执行:T-SQL里面有声明变量的参数化查询?

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查询

+0

究竟是什么错误您收到?我没有看到任何你的SQL查询无法解释的原因,我一直都在使用这种技术。 –

回答

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 

你还有你所有的参数,和你如您的示例中那样,从dbo.CREAccount表中确定AccountKey的值。

也许你需要思考的问题没有值在表中找到的情况下,为AccountKey提供一个“默认”值...

或者,如果不出于某种原因,那么我可能会只是包这两个或三个T-SQL语句到一个存储过程,你可以带参数调用,并让该程序处理所有你可能需要额外的步骤....

+0

这就是我要输入的内容:) – bluevector

+0

我不想要SP,是的,像我这样做的关键点是因为AccountKey可以是NULL - 所以你的SQL不会插入任何东西。我完全是这样的,但新的要求,允许在AccountKey – katit

+0

NULLs我希望有关于如何使用参数和使用脚本内的参数答案 – katit

0

你有没有尝试包括@AccountKey为一个sqlparmae​​ter,但改变它的方向输出?这样,你仍然应该能够选择一个值,它根据反馈到marc_s的回答

1

,你总是可以让你的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) 

如果你想为帐号键的默认值这将是很容易合并的结果