kbvishnu
kbvishnu

Reputation: 15630

Adding parameters to a dynamic sql query

My sql procedure is

 SET @query='UPDATE '+@tbl+' SET  auth_Date='''+@authDate+'''
    ,authorized_By_ID=@AuthID
    ,authorized=1 WHERE '+@col+'=@Id;
    IF(@@ERROR=0) SET @reVal=1 ELSE SET @reVal=-1' 


    EXECUTE sp_executesql @query, N'@reVal int OUTPUT', 
    @reVal,N'@AuthID int',@AuthID,N'@Id int',@Id

Here @AuthID is Datetime, @AuthID and @Id is int

1) How can I pass arguments . 2) There is an error is coming Conversion failed when converting date and/or time from character string.

Upvotes: 1

Views: 9361

Answers (1)

Remus Rusanu
Remus Rusanu

Reputation: 294227

You pass argument definition in the second parameter, followed by the arguments, in the order declared:

EXECUTE sp_executesql @query, 
    N'@AuthID int, @Id int, @reVal int OUTPUT', 
    @AuthID, @Id, @reVal OUTPUT;

Any reason why you don't pass @authDate also as a parameter? specially since datetime types are notoriously error prone when converted to strings, due to locale settings.

Last, you should use TRY/CATCH blocks instead of @@ERROR checks.

Upvotes: 5

Related Questions