在sql中使用变量作为完整的where子句

时间:2014-03-12 13:42:33

标签: sql-server tsql variables where

我正在尝试这样做:

DECLARE @str varchar(max)
  SET @str='BEGIN        
              SELECT count(*) FROM eCareMembers
            END'        
  EXEC(@str)
SET @cnt2=cast(@str as bigint)
SELECT cast(@cnt2 as varchar(max)) as usercount, *.a from user a      

但我收到错误:Error converting data type varchar to bigint.

2 个答案:

答案 0 :(得分:0)

我明白。试试这个:

SELECT (SELECT count(*) FROM eCareMembers) as usercount, *.a from user a

答案 1 :(得分:0)

我不清楚你要做什么,但如果你想执行一些动态SQL并将一些结果捕获到变量中,你应该使用sp_executesql

declare @Cnt int;
declare @sql nvarchar(max);
set @sql = N'select @c = COUNT(*) from sys.objects';
exec sp_executesql @sql,N'@c int output',@Cnt output

print @Cnt

(对我来说,打印83)。