将sql结果作为单个字符串返回

时间:2013-12-11 09:16:34

标签: database sql-server-2008 select-query

我有以下查询返回超过1个结果(最多不超过10个!),如何将所有结果作为单个字符串返回?

SELECT DISTINCT(e.Username)
FROM TblLeaveEmployee l
JOIN TblLeaveApprovalsBy a on l.EmployeeId = a.UserID
JOIN TblEmployee e on l.EmployeeId = e.id
where l.EmployeeId IN 
  (select UserID 
   FROM TblLeaveApprovalsBy 
   WHERE ApprovalUserID IN
     (SELECT ApprovalUserID from TblLeaveApprovalsBy where UserID = 77))

尝试使用STUFF如下,但它不起作用:

DECLARE @CodeNameString varchar(100)
SELECT 
   @CodeNameString = STUFF(
SELECT DISTINCT(e.Username)
FROM TblLeaveEmployee l
JOIN TblLeaveApprovalsBy a on l.EmployeeId = a.UserID
JOIN TblEmployee e on l.EmployeeId = e.id
where l.EmployeeId IN 
  (select UserID 
   FROM TblLeaveApprovalsBy
   WHERE ApprovalUserID IN
     (SELECT ApprovalUserID from TblLeaveApprovalsBy where UserID = 77)))

3 个答案:

答案 0 :(得分:1)

   DECLARE @CodeNameString VARCHAR(MAX)=NULL
   SELECT @CodeNameString = COALESCE(@CodeNameString+',' ,'') + Username 
   FROM
   (
   SELECT DISTINCT(e.Username) Username
   FROM TblLeaveEmployee l
   JOIN TblLeaveApprovalsBy a on l.EmployeeId = a.UserID
   JOIN TblEmployee e on l.EmployeeId = e.id
   where   l.EmployeeId IN (select UserID FROM TblLeaveApprovalsBy
              WHERE ApprovalUserID IN(SELECT ApprovalUserID from TblLeaveApprovalsBy    where UserID = 77))) x
   SELECT @CodeNameString

答案 1 :(得分:1)

DECLARE t CURSOR FOR  
SELECT DISTINCT(e.Username)
FROM TblLeaveEmployee l
JOIN TblLeaveApprovalsBy a on l.EmployeeId = a.UserID
JOIN TblEmployee e on l.EmployeeId = e.id
where l.EmployeeId IN 
(select UserID 
   FROM TblLeaveApprovalsBy 
   WHERE ApprovalUserID IN
     (SELECT ApprovalUserID from TblLeaveApprovalsBy where UserID = 77))

open t

declare @v varchar(255)
declare @Res varchar(max)
 set @Res = ''
 set @v = ''
FETCH NEXT FROM t into @v
while (@@FETCH_STATUS = 0) begin
    set @Res = @Res + @v + '|'
    FETCH NEXT FROM t into @v
end
print @Res

close t
deallocate t

答案 2 :(得分:0)

如果您有大量的行,这将是一个问题。

试试这个

DECLARE t CURSOR FOR  
select Col1 from [Table] where crite1 = ???

open t

declare @v varchar(255)
declare @Res varchar(max)
 set @Res = ''
 set @v = ''
FETCH NEXT FROM t into @v
while (@@FETCH_STATUS = 0) begin
    set @Res = @Res + @v + '|'
    FETCH NEXT FROM t into @v
end
print @Res

close t
deallocate t