2013-10-03 63 views
1

我有三個表,其中一個表由employeeId連接。普通的SQL語句在加入和在一列中返回三個值 - 但是,我需要一個字符串來顯示這些值,即代替sql curser只返回一個值

Harry Tuttle 
Sam Lowrey 
Jack Lint 

我需要返回的

Harry Tuttle, Sam Lowrey, Jack Lint 

我創建了一個存儲過程並使用遊標(我的第一次嘗試),它包含在下面。唯一的問題是它執行並返回

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次(I得到6個生成的IDE幀,每個包含一個名稱但各不相同:

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

))。

我正在使用Sybase。有任何想法嗎?

+0

每當您進入'@ advisor_name'時,您都會覆蓋之前的內容。你需要一個不同的變量來積累答案。 – Laurence

+0

不知道如何實現這個目標? –

回答

1

您一直覆蓋您的@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 
+0

工作過。看看你的解決方案,現在看起來如此明顯...... –