简体   繁体   中英

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.

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 .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM