sql游标只返回一个值

时间:2013-10-03 22:19:15

标签: sql cursor sybase

我有三个表,其中一个表由employeeId连接。一个普通的sql语句进行连接并在一列中返回三个值 - 但是,我需要将这些值显示为单个String,即代替

Harry Tuttle  
Sam Lowrey  
Jack Lint

我需要返回

Harry Tuttle, Sam Lowrey, Jack Lint

我已经创建了一个存储过程并使用了一个游标(我的第一次尝试),它包含在下面。唯一的问题是它是execytes并返回

Sam Lowrey,

每次执行。 proc看起来像

create procedure sp_ac_temp (@assignmment_id int)
as

/* declare local variables used for fetch */  
declare @advisor_name varchar(100)  
/* cursor to get each advisor name */  
declare advisor_fetch cursor for  
        select e.first_name + ' ' + e.last_name + ', '  
          from assign a  
    inner join advisor fa on a.assignment_id = fa.assignment_id  
    inner join employee e on fa.employee_id = e.employee_id  
  where a.assignment_id = @assignmment_id  

open advisor_fetch   
fetch advisor_fetch  
        into @advisor_name   
if (@@sqlstatus = 2)  
begin  
    close advisor_fetch  
    return  
end  


/* if cursor result set is not empty, process each row of information */  
while (@@sqlstatus = 0) 
begin  
    --if (@advisor_name != NULL)  
    begin  
        select @advisor_name = @advisor_name + '! '  

    end   
    fetch advisor_fetch into @advisor_name  

    select @advisor_name  

end  

我可以改变脚本并在不同的SquirrleSQL窗格上生成输出,例如,如果我将while循环段改为:

while (@@sqlstatus = 0)
begin
    --if (@advisor_name != NULL)
    begin
        select @advisor_name = @advisor_name + '! '
        select @advisor_name --this here
    end 
    fetch advisor_fetch into @advisor_name

    select @advisor_name

end

这表明光标循环了6次(我生成了6个IDE框架,每个框架包含一个名称,但它们各不相同:

Harry Tuttle, !
Sam Lowrey,  
Sam Lowrey, ! 
Jack Lint, 
Jack Lint, 
Jack Lint, ! 

))。

我正在使用Sybase。有什么想法吗?

1 个答案:

答案 0 :(得分:2)

您将继续覆盖@advisor_name变量。您需要将答案累积到另一个变量中,此处为@combined_name

我不知道sybase,但我也假设您需要在使用后关闭/取消分配光标。

create procedure sp_ac_temp (@assignmment_id int) as
declare @advisor_name varchar(100)  
declare @combined_name varchar(1000) -- variable to accumulate answer

select @combined_name = ''

declare advisor_fetch cursor for  
    select 
        e.first_name + ' ' + e.last_name + ', '  
    from 
        assign a inner join 
        advisor fa on a.assignment_id = fa.assignment_id inner join 
        employee e on fa.employee_id = e.employee_id  
    where
        a.assignment_id = @assignmment_id  

open advisor_fetch   
fetch advisor_fetch into @advisor_name   
if (@@sqlstatus = 2)  
begin  
    close advisor_fetch  
    return  
end  

/* if cursor result set is not empty, process each row of information */  
while (@@sqlstatus = 0) 
begin  
    select @combined_name = @combined_name + @advisor_name --append next advisor
    fetch advisor_fetch into @advisor_name  
end  
select @combined_name