2011-06-06 87 views
2

我有一個從表中返回多行的查詢。然後我將該查詢轉換爲這一個:SQL SERVER中的單行分隔記錄查詢結果

;with mycte as 
(select s.FirstName + ' ' + s.LastName as Name from ClientStaff cs 
left outer join Staff s on s.Id = cs.StaffId 
left outer join GeneralStatus gs on gs.Id = s.StatusId 
where cs.ClientId = @clientId and gs.Name = 'Active') 

select @staff = (select distinct staff = REPLACE(REPLACE(REPLACE((select Name AS [data()] FROM mycte a 
order by a.Name for xml path),'</row><row>',', '),'</row>',''),'<row>','') from mycte b) 

它在單個以逗號分隔的行中返回這些行。 現在我不想用逗號分隔的值,而是想要單行分隔的值。 任何人都可以告訴我,如果有可能嗎?

在此先感謝。

回答

3
declare @staff varchar(max) 

;with mycte as 
(
    select distinct s.FirstName + ' ' + s.LastName as Name 
    from ClientStaff cs 
     left outer join Staff s on 
      s.Id = cs.StaffId 
     left outer join GeneralStatus gs on 
     gs.Id = s.StatusId 
    where cs.ClientId = @clientId and gs.Name = 'Active' 
) 
select @staff = isnull(@staff + char(13), '') + Name 
from mycte b 

print @staff 
+0

它仍然以逗號分隔。我需要線分離。 – asma 2011-06-06 04:50:55

+0

@asma - 你需要使用char(13)。更新了答案。 – 2011-06-06 04:55:27

+0

+1,但取決於輸出是否意味着在消費之後額外處理或者直接用於顯示,最好使用'CHAR(13)+ CHAR(10)'作爲分隔符。 – 2011-06-06 05:20:52