发送存储过程的输出,以逗号分隔而不是多行

时间:2019-03-08 00:43:42

标签: sql stored-procedures sql-server-2005 temp-tables table-variable

我有一个存储过程,该过程返回5列的多行:

SELECT Travel, ID, Dept, Role, Country 
FROM TravelManager

例如,我得到:

DName   ID   Dept  Role   Country
----------------------------------
Travel  23   HR    H      USA
Travel  29   MR    M      AUS
Travel  32   FI    M      UK

我有什么办法可以将其作为逗号分隔的值发送,因为第一列是相同的,我只希望发送一行而不在多行中复制名称,还希望仅将一行作为逗号分隔的值发送给其他列。

有什么想法和更好的方法吗?另外,我该如何修改选择查询?

我的第一列是存储过程输入,因此也要返回它:)

我正在考虑临时表或表变量,但如果这样做怎么办?请帮助

1 个答案:

答案 0 :(得分:1)

可以使用光标完成

declare @Travel nvarchar(max)
declare @ID int
declare @Country nvarchar(max)
declare @Dept nvarchar(max)
declare @Role nvarchar(max)

declare @string nvarchar(max)

declare cursor1 cursor for
     SELECT  ID, Dept, Role, Country 
     FROM TravelManager

set @string = '';

open cursor1

fetch next from cursor1 into  @ID, @Dept, @Role, @Country

while (@@Fetch_Status <> -1)    
begin
    set @string += convert(varchar(10), @ID) + ',' +
                   @Dept + ',' + @Role + ',' + @Country + char(13) // char(13) for new line
    fetch next from cursor1 into  @ID, @Dept, @Role, @Country
end

close cursor1
deallocate cursor1


select  @string as ReturnValue

char(13)添加回车符,否则您可以添加\ n我猜

编辑:删除了选择旅行

相关问题