3

我有一个存储过程,它接受一个包含单个值的参数。我想将一组值一个一个地传递给过程,并将组合结果放入一个表中。这可能吗 ?

目前我正在使用游标在循环中执行过程,但只能获得传递集合中第一个值的结果。

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

如果这太模糊/不清楚/愚蠢,有人可以为我提供替代方案吗?非常感谢任何帮助。谢谢。

4

2 回答 2

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
于 2013-01-25T13:09:16.047 回答
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

SQLFiddle上的简单示例

于 2013-01-25T17:30:29.617 回答