从函数 - SQL Server返回存储过程中的多个值

时间:2016-06-20 06:03:53

标签: sql-server tsql stored-procedures

SP1

ALTER procedure [dbo].[sp1]            
as             
begin                        
DECLARE @od varchar(255)
EXEC @od =dbo.getFn

SELECT CMSA.A,CMSB.B, @OD
FROM CMSA INNER JOIN CMSB
GROUP BY CMSA.A, CMSB.B
end

fn1的

ALTER FUNCTION [dbo].[getFn]()
returns varchar(255)
as 
BEGIN 
DECLARE @Desc1 varchar(200)
DECLARE @Desc2 varchar(200)
DECLARE c1  CURSOR FOR
SELECT CMSC.C
FROM   CMSC INNER JOIN CMSB INNER JOIN CMSC
WHERE CMSC.C = "HELLO" OR CMSC.C = "GOODBYE"
GROUP BY CMSC.C
Open c1
FETCH NEXT FROM c1 INTO @Desc1
set @Desc2=@Desc1 
CLOSE c1
deallocate c1
Return @Desc2
end

只是说CMSC的现有值是HELLO和GOODBYE,我想在函数的存储过程中显示这两个值。例如,

CMSA.A, CMSB.B, HELLO
CMSA.A, CMSB.B, GOODBYE

但是现在,我只能显示一个输出而不是两个输出,如上所述。我该如何解决这个问题?

1 个答案:

答案 0 :(得分:0)

功能

该函数似乎是错误的,因为内部联接没有ON语句。

ALTER FUNCTION [dbo].[getFn]()
returns @table TABLE (value varchar(255))
as 
BEGIN 
    DECLARE @Desc1 varchar(200)
    DECLARE @Desc2 varchar(200)

    DECLARE c1  CURSOR FOR

    SELECT CMSC.C
    FROM   CMSC 
    INNER JOIN CMSB 
    INNER JOIN CMSC
    WHERE CMSC.C = "HELLO" OR CMSC.C = "GOODBYE"
    GROUP BY CMSC.C

    Open c1
    FETCH NEXT FROM c1 INTO @Desc1
    set @Desc2=@Desc1 
    INSERT INTO @table VALUES (@Desc2)
    CLOSE c1
    deallocate c1

    Return 
end

<强> SP

再次,SP的语法也是错误的,因为INNER JOIN中缺少ON语句。

ALTER procedure [dbo].[sp1]            
as             
begin                        
DECLARE @od varchar(255)
EXEC @od =dbo.getFn

SELECT CMSA.A,CMSB.B, a.Value
FROM CMSA INNER JOIN CMSB
INNER JOIN (SELECT * FROM dbo.getFn()) a
GROUP BY CMSA.A, CMSB.B
end

可能是内部联接或交叉联接,具体取决于您是否有要参考的字段