我希望从Exec(@sql)
获取值并分配给@Rowcount(int)
这是我的问题:
'SET @RowCount = (select count(*)
FROM dbo.Comm_Services
WHERE CompanyId = '+cast(@CompanyId as char)+' and '+@condition+')'
答案 0 :(得分:82)
一方面,您可以使用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);
答案 1 :(得分:0)
这是我的程序
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
答案 2 :(得分:0)
今天正在玩这个...我相信你也可以使用@@ ROWCOUNT,就像这样:
DECLARE @SQL VARCHAR(50)
DECLARE @Rowcount INT
SET @SQL = 'SELECT 1 UNION SELECT 2'
EXEC(@SQL)
SET @Rowcount = @@ROWCOUNT
SELECT @Rowcount
然后将“SELECT 1 UNION SELECT 2”替换为您没有计数的实际选择。我建议你在选择中加1,就像这样:
SELECT 1
FROM dbo.Comm_Services
WHERE....
....
(与放置SELECT *相反)
希望有所帮助。
答案 3 :(得分:0)
声明@nReturn int = 0 EXEC @nReturn =存储过程
答案 4 :(得分:-1)
如果我理解正确,(我可能不会)
'SELECT @RowCount = COUNT(*)
FROM dbo.Comm_Services
WHERE CompanyId = ' + CAST(@CompanyId AS CHAR) + '
AND ' + @condition