从exec(@sql)返回值

我想从Exec(@sql)获取值并赋值给@Rowcount(int)

这是我的查询:

 'SET @RowCount = (select count(*) FROM dbo.Comm_Services WHERE CompanyId = '+cast(@CompanyId as char)+' and '+@condition+')' 

一方面你可以使用sp_executesql:

 exec sp_executesql N'select @rowcount=count(*) from anytable', N'@rowcount int output', @rowcount output; 

另一方面,你可以使用临时表:

 declare @result table (rowcount int); insert into @result (rowcount) exec (N'select count(*) from anytable'); declare @rowcount int = (select top (1) rowcount from @result); 

如果我理解正确,(我可能不)

 'SELECT @RowCount = COUNT(*) FROM dbo.Comm_Services WHERE CompanyId = ' + CAST(@CompanyId AS CHAR) + ' AND ' + @condition 

这是我的程序

 CREATE PROC sp_count @CompanyId sysname, @codition sysname AS SET NOCOUNT ON CREATE TABLE #ctr ( NumRows int ) DECLARE @intCount int , @vcSQL varchar(255) SELECT @vcSQL = ' INSERT #ctr FROM dbo.Comm_Services WHERE CompanyId = '+@CompanyId+' and '+@condition+')' EXEC (@vcSQL) IF @@ERROR = 0 BEGIN SELECT @intCount = NumRows FROM #ctr DROP TABLE #ctr RETURN @intCount END ELSE BEGIN DROP TABLE #ctr RETURN -1 END GO 

今天正在玩这个…我相信你也可以使用@@ ROWCOUNT,就像这样:

 DECLARE @SQL VARCHAR(50) DECLARE @Rowcount INT SET @SQL = 'SELECT 1 UNION SELECT 2' EXEC(@SQL) SET @Rowcount = @@ROWCOUNT SELECT @Rowcount 

然后用你的实际selectreplace“SELECT 1 UNION SELECT 2”而不计数。 我build议在你的select中join1,就像这样:

 SELECT 1 FROM dbo.Comm_Services WHERE.... .... 

(而不是把SELECT *)

希望有所帮助。

声明@nReturn int = 0 EXEC @nReturn =存储过程