简体   繁体   中英

How to pass an output variable in dynamic sql query

I was reviewing a stored procedure where I found piece of code below. Looking at the code, my perception is that we are creating a variable named @QuestionInclude and passing its value in dynamic sql statement. But how this code is working?

This is something strage and new to me.

declare @QuestionInclude varchar(10)
select @sqln =  'select @QuestionInclude = 1 from ##Stg_Prelim' 
exec sp_executesql @sqln,N'@QuestionInclude varchar(10) output',@QuestionInclude output

may be this will help you

http://msdn.microsoft.com/en-us/library/ms188001.aspx

procedure sp_executesql have parameters @stmt , which is actual statement to run, @params - declaration of parameters, and then all parameters declared in @params

It's also better to pass parameters by names

declare @QuestionInclude varchar(10), @stmt nvarchar(max), @params nvarchar(max)

select @stmt = 'select @QuestionInclude = 1 from ##Stg_Prelim'
select @params = '@QuestionInclude varchar(10) output'

exec sp_executesql
    @stmt = @stmt,
    @params = @params,
    @QuestionInclude = @QuestionInclude output

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