日期:2014-05-18  浏览次数:20546 次

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


提示报错,请高手指教?

------解决方案--------------------
SQL code


create table #order(id int,type int,sort int,Pid int)

insert into #order(id,type,sort,Pid)
select 1,1,20,20  union all
select 2,1,20,20  union all
select 3,1,20,20  union all
select 4,1,20,20  union all
select 5,0,20,20  union all
select 6,0,21,20  

select * from #order

declare @str nvarchar(max)
declare @tem int


set @str=' type=1 or sort>20 '
set @str=N'select @tem_1=sum(id) from #order where ' +@str+ N' and Pid=20'
print @str
exec sp_executesql @str,N'@tem_1 int output',@tem_1=@tem output
select @tem

--or
set @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 @str
select @tem=total from @tb_value
select @tem