如何得到动态SQL中取得的值?

问题描述:

要求表A的记录总和,可以用
select @cnt=count() from A where ......
但是当我的条件是动态拼凑的字符串,那么就必须用
set @sql='select @cnt=count(
) from A where '+'.......'
exec(@sql)
但这样行不通,除了用那烦琐的游标还有其他更简单的办法吗?

另外,如果求两个表的记录总和能不能在一条select语句中实现啊?
比如“select count(A),count(B) from A,B”当这样不行啊?
---------------------------------------------------------------

回答:

declare @sql nvarchar(2000),@count int
set @sql=N'select @cnt=count(*) from A where '+'.......'
exec sp_executesql @sql,N'@cnt int output',@count output
print @count
这样即可

select count(A),count(B) from A,B
这样写当然不行了.
但这样写就可以了:
select countA,countB from
(select count() countA from A) ss,
(select count(
) countB from B) tt

Published At
Categories with 数据库类
Tagged with
comments powered by Disqus