2

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

Harry Tuttle  
Sam Lowrey  
Jack Lint

我需要返回

Harry Tuttle, Sam Lowrey, Jack Lint

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

Sam Lowrey,

每次执行。过程看起来像

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。有任何想法吗?

4

1 回答 1

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
于 2013-10-03T23:14:36.580 回答