日期:2014-05-17  浏览次数:20526 次

SQLSERVER2008在存储过程中执行动态SQL语句的问题
我想要达到的效果就是:在根据条件返回记录数后,能够根据返回的记录数去继续执行下面的SQL语句,进而返回结果,同时在页面上显示的结果为10:
CREATE proc select_areasAssociation_sort
@condition varchar(100)
as
declare @regularSortCount int,@sortCount int,@sql varchar(500)
--返回固态排名的记录数
set @sql='select '+@regularSortCount+'=COUNT(1) from AreasAssociation 
where RegularSort is not null and RegularSort>0 and '+@condition
exec @sql
--返回动态排名的记录数
set @sql='select '+@sortCount+'=COUNT(1) from AreasAssociation 
where Sort is not null and Sort>0 and '+@condition
exec @sql
--当动态排名和固定排名都不存在时
if(@regularSortCount=0 and @sortCount=0)
begin
--select top 10 * from AreasAssociation where PositionID=2 
--and CrabType=1 ORDER BY newID() 
return
end
--当固定排名存在而动态排名不存在时
else if(@regularSortCount>0 and @sortCount=0)
begin
。。。。。。。
但是执行到”--返回固态排名的记录数”的时候就报错了,各位大侠给点建议吧。。。
动态SQL语句 执行存储过程 返回记录数

------解决方案--------------------
一个是@regularSortCount变量是int型,需要转换成字符型才能与字符拼接
另一个是要想用动态sql输出@regularSortCount变量需要用sp_executesql来执行

declare @sql nvarchar(max),@count int
set @sql='select @c=count(1) from test '
exec sp_executesql @sql,N'@c int output',@count output
select @count

------解决方案--------------------
引用:
那紧接着上面的SQL语句中如下代码,不能执行,你帮我看看下:if(@sortCount>10)
begin
set @sql='select top 10 * from AreasAssociation
where Sort is not null and Sort>0 and '+@condition+' order by Sort'
end
exec @sq……

这个要用括号括起来,不然会认为是存储过程,exec(@sql)