我有桌子。
查询ID | 查询 |
---|---|
1 | 从雇员姓名中选择计数(*)不为空 |
2 | 从 id 不为空的部门中选择 count(*) |
现在我正在编写一个存储过程来运行查询并将结果存储在目标表中,如下所示:
查询ID | 结果 |
---|---|
1 | 2300 |
2 | 4500 |
但是我使用此存储过程得到如下表所示的结果:
查询ID | 结果 |
---|---|
1 | 1 |
2 | 1 |
代码:
CREATE PROCEDURE ExecuteQueriesAndStoreResults
AS
BEGIN
DECLARE @query NVARCHAR(255);
DECLARE @queryID NVARCHAR(255);
-- Declare variables for query results
DECLARE @queryResult NVARCHAR(255);
-- Declare a cursor to loop through TableA
DECLARE @curQuery CURSOR;
SET @curQuery = CURSOR FOR
SELECT Query, QueryID
FROM TableA;
OPEN @curQuery;
FETCH NEXT FROM @curQuery INTO @query, @queryID;
WHILE @@FETCH_STATUS = 0
BEGIN
-- Execute the dynamic query
EXEC(@query);
-- Capture the result of the dynamic query
SET @queryResult = @@ROWCOUNT; -- Store the result as needed
-- Insert the result along with the QueryID into ResultsTable
INSERT INTO ResultsTable (QueryID, Result)
VALUES (@queryID, @queryResult);
FETCH NEXT FROM @curQuery INTO @query, @queryID;
END;
CLOSE @curQuery;
DEALLOCATE @curQuery;
END;
查询ID | 结果 |
---|---|
1 | 2300 |
2 | 4500 |
您每次查询都会得到
1
,因为:
SELECT COUNT(*) FROM sys.all_columns;
SELECT @@ROWCOUNT; -- always 1!
假设查询模式是 always...
SELECT {something like a count} and only one row
...你可以这样做:
-- somewhere way above:
DECLARE @sql nvarchar(max);
-- then inside the cursor:
SET @sql = N'WITH cte(rcount) AS ('
+ @query + ') SELECT @QueryID, rcount FROM cte;';
INSERT dbo.ResultsTable(QueryID, Result)
EXEC sys.sp_executesql @sql, N'@QueryID int', @QueryID;
使用
sp_executesql
而不是 exec
来执行动态 SQL。它允许来回传递参数。
declare @stmt nvarchar(max);
declare @params nvarchar(max);
declare @rowcount int;
set @stmt = N'select @rowcount = count(*) from dbo.YOURTABLE where ID is not null;'
set @params = N'@rowcount int output';
exec sp_executesql @stmt = @stmt
, @params = @params
, @rowcount = @rowcount output;
select @rowcount;