MSSSQL变量加引号

declare @num int 
declare @bb nvarchar(2000), @cc nvarchar(2000),@sqls nvarchar(2000)
set @num=CONVERT(int,03)
set @bb=''  --赋值,不然可能叠加为null
set @cc=''
while @num>0
     begin   --添加引号要注意,不然报错
        set @bb+=' (case when rmonth='+convert(varchar,@num)+' then rmonth else 0 end) '+''''+convert(varchar,@num)+''''+'月份,'
        if @num<>1
           begin
                set @cc+=' case when rmonth=90'+convert(varchar,@num)+' then rmonth else 0 end '+''''+'90'+convert(varchar,@num)+''''+'月份,'
           end
        set @num=@num-1
     end
            
set @sqls=N'select '+@bb+left(@cc,len(@cc)-1)+''+@bb+left(@cc,len(@cc)-1)+' from #temp order by rmonth'
exec sp_executesql @sqls  
go

你可能感兴趣的:(MSSSQL变量加引号)