2011-06-06 32 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