从循环存储过程返回单个记录集
Returning a single recordset from a looping stored procedure
我不太喜欢将查询放入循环中,但是我需要 运行 一个循环并执行存储过程的查询。
我已经拥有的东西有效,但是结果在单独的结果集中 returned,其方式通常是多个查询 运行 一个接一个地进行。
我需要一个结果集中的所有结果,就像 UNION 给我的方式一样。
这是我所拥有的示例:
-- Insert statements for procedure here
declare @id int
--declare @field2 int
declare cur CURSOR LOCAL for
-- Build examples to loop through
SELECT 1 AS id
UNION
SELECT 2 AS id
UNION
SELECT 3 AS id
open cur
fetch next from cur into @id
while @@FETCH_STATUS = 0 BEGIN
--execute your stored procedure on each row
SELECT @id
fetch next from cur into @id
END
close cur
deallocate cur
这将 return 以下内容:
-----------
1
(1 row(s) affected)
-----------
2
(1 row(s) affected)
-----------
3
(1 row(s) affected)
不过我需要:
id
-----------
1
2
3
(3 row(s) affected)
能否将结果放入#Temp table?
在您的日常生活中添加一个临时工 table
Create Table #tbl
(
id Int
)
你的日常安排
-- Insert statements for procedure here
declare @id int
--declare @field2 int
declare cur CURSOR LOCAL for
-- Build examples to loop through
SELECT 1 AS id
UNION
SELECT 2 AS id
UNION
SELECT 3 AS id
open cur
fetch next from cur into @id
while @@FETCH_STATUS = 0 BEGIN
--execute your stored procedure on each row
Insert Into #Tbl SELECT @id --ON EACH LOOP, INSERT ID to TEMP TABLE
fetch next from cur into @id
END
Select * From #Tbl --Present the results of the TEMP TABLE
close cur
deallocate cur
Drop Table #tbl --Drop your TEMP TABLE
结果:
id
1
2
3
我不太喜欢将查询放入循环中,但是我需要 运行 一个循环并执行存储过程的查询。
我已经拥有的东西有效,但是结果在单独的结果集中 returned,其方式通常是多个查询 运行 一个接一个地进行。
我需要一个结果集中的所有结果,就像 UNION 给我的方式一样。
这是我所拥有的示例:
-- Insert statements for procedure here
declare @id int
--declare @field2 int
declare cur CURSOR LOCAL for
-- Build examples to loop through
SELECT 1 AS id
UNION
SELECT 2 AS id
UNION
SELECT 3 AS id
open cur
fetch next from cur into @id
while @@FETCH_STATUS = 0 BEGIN
--execute your stored procedure on each row
SELECT @id
fetch next from cur into @id
END
close cur
deallocate cur
这将 return 以下内容:
-----------
1
(1 row(s) affected)
-----------
2
(1 row(s) affected)
-----------
3
(1 row(s) affected)
不过我需要:
id
-----------
1
2
3
(3 row(s) affected)
能否将结果放入#Temp table?
在您的日常生活中添加一个临时工 table
Create Table #tbl
(
id Int
)
你的日常安排
-- Insert statements for procedure here
declare @id int
--declare @field2 int
declare cur CURSOR LOCAL for
-- Build examples to loop through
SELECT 1 AS id
UNION
SELECT 2 AS id
UNION
SELECT 3 AS id
open cur
fetch next from cur into @id
while @@FETCH_STATUS = 0 BEGIN
--execute your stored procedure on each row
Insert Into #Tbl SELECT @id --ON EACH LOOP, INSERT ID to TEMP TABLE
fetch next from cur into @id
END
Select * From #Tbl --Present the results of the TEMP TABLE
close cur
deallocate cur
Drop Table #tbl --Drop your TEMP TABLE
结果:
id
1
2
3