获取存储过程中以逗号分隔的值

时间:2013-04-11 10:39:35

标签: sql-server-2008

我在sqlserver中有一个表

UserID(PK)    Name    PhoneNumber
1             Test     123456
2             Test1    356456

另一张有上表FK的表

 ID    RequestID   UserID(FK)
  1      20123        1
  2      20245        1
  3      21545        2

我需要以下结果

UserID    Name      phoneNumber  RequestID
 1        Test      123456       20123,20245
 2        Test1      356456       21545 

我曾经使用过连接,但每行都有多条记录,但我需要上面的结果。 任何人都可以帮助我获得这种类型的输出吗?

2 个答案:

答案 0 :(得分:1)

SELECT [UserID]
     , [Name]
     ,[PhoneNumber]
     , stuff((SELECT distinct ' ,'+ CAST(RequestID AS VARCHAR)
         FROM [Request] 
         WHERE (UserID = [PK].UserID) 
         FOR XML PATH ('')),1,2,''
      ) AS Request1
FROM [PK]

<强> I borrowed some concept from here

<强> SQL Fiddle

答案 1 :(得分:1)

有几种不同的方法可以做到这一点。

使用FOR XML PATHSTUFF

select u.userid,
  u.name,
  u.phonenumber,
  STUFF((SELECT distinct ', ' + cast(r.requestid as varchar(10))
         from requests r
         where u.userid = r.userid
            FOR XML PATH(''), TYPE
            ).value('.', 'NVARCHAR(MAX)') 
        ,1,2,'') requests
from users u;

请参阅SQL Fiddle with Demo

或者您可以使用CROSS APPLYFOR XML PATH

select u.userid,
  u.name,
  u.phonenumber, 
  left(r.requests, len(r.requests)-1) requests
from users u
cross apply
(
  select cast(r.requestid as varchar(10)) + ', '
  from  requests r
  where u.userid = r.userid
  FOR XML PATH('')
) r (requests);

请参阅SQL Fiddle with Demo