SQL存储过程给变量赋值
declare @str nvarchar(max)
declare @tem int
set @str=' and type=1 or sort>20 '
set @tem=select sum(id) from order where +@str+ and Pid=20
提示报错,请高手指教?
[解决办法]
create table #order(id int,type int,sort int,Pid int)insert into #order(id,type,sort,Pid)select 1,1,20,20 union allselect 2,1,20,20 union allselect 3,1,20,20 union allselect 4,1,20,20 union allselect 5,0,20,20 union allselect 6,0,21,20 select * from #orderdeclare @str nvarchar(max)declare @tem intset @str=' type=1 or sort>20 'set @str=N'select @tem_1=sum(id) from #order where ' +@str+ N' and Pid=20'print @strexec sp_executesql @str,N'@tem_1 int output',@tem_1=@tem outputselect @tem--orset @str=' type=1 or sort>20 'set @str=N'select sum(id) from #order where ' +@str+ N' and Pid=20'declare @tb_value table(total int)insert into @tb_value(total)exec sp_sqlexec @strselect @tem=total from @tb_valueselect @tem