我有一个存储过程,它接受一个包含单个值的参数。 我想逐个将一组值传递给过程,并将组合结果合并到一个表中。这可能吗?
目前我正在使用游标在循环中执行过程,但只获得了从集合中传递第一个值的结果。
declare @clientid varchar(10)
create table #tmpp(secid varchar(10))
insert into #tmpp values(2319)
insert into #tmpp values(2855)
insert into #tmpp values(1303)
declare cur CURSOR LOCAL for
select secid from #tmpp
open cur
fetch next from cur into @seclientid
while @@FETCH_STATUS = 0 BEGIN
exec getReportforclient @clientid
fetch next from cur into @clientid
END
close cur
deallocate cur
drop table #tmpp
如果这太混淆/不清楚/愚蠢,有人可以给我一个替代方案吗? 任何帮助都非常感谢。感谢。
答案 0 :(得分:1)
可能有一种方法可以不使用游标,但是如果不查看存储过程,我们就无法帮助过多。您可以创建一个表(临时或非临时),其结构与sp的结果相同,并将结果插入其中。像这样:
DECLARE @clientid VARCHAR(10)
CREATE TABLE #tmpp(secid VARCHAR(10))
INSERT INTO #tmpp VALUES(2319)
INSERT INTO #tmpp VALUES(2855)
INSERT INTO #tmpp VALUES(1303)
CREATE TABLE #Results(col1 INT, col2.... -- create the table that will hold your
-- results
DECLARE cur CURSOR LOCAL for
SELECT secid
FROM #tmpp
OPEN cur
FETCH NEXT FROM cur INTO @seclientid
WHILE @@FETCH_STATUS = 0
BEGIN
INSERT INTO #Results
exec getReportforclient @clientid
FETCH NEXT FROM cur INTO @clientid
END
CLOSE cur
DEALLOCATE cur
DROP TABLE #tmpp
SELECT *
FROM #Results
答案 1 :(得分:1)
没有CURSOR的循环
IF OBJECT_ID('tempdb.dbo.#tmpp') IS NOT NULL DROP TABLE #tmpp
CREATE TABLE #tmpp(Clientid varchar(10))
INSERT #tmpp values(2319), (2855), (1303)
IF OBJECT_ID('tempdb.dbo.#Results') IS NOT NULL DROP TABLE #Results
CREATE TABLE #Results(--output columns of procedure)
DECLARE @Clientid int = (SELECT MIN(Clientid) FROM #tmpp)
WHILE (@Clientid IS NOT NULL)
BEGIN
INSERT INTO #Results
EXEC getReportforclient @Clientid
SELECT @Clientid = MIN(Clientid) FROM #tmpp WHERE Clientid > @Clientid
END
上的简单示例