1

我有以下查询返回超过 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)))
4

3 回答 3

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
于 2013-12-11T09:41:15.293 回答
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
于 2013-12-11T09:51:52.400 回答
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
于 2013-12-11T09:31:23.000 回答