-3

这是我的桌子

  StudentID    Name
    ----------   ------
      1          Mary
      2          John
      3          Peter
      4          Edwards

   ClassID      StudentIDs
    --------    -----------
      1          1,2
      2          3,4

    **Output Expected**

    ClassID   Names
    -------   -------

        1      Mary,John
        2      Peter,Edwards
4

3 回答 3

3

解决方案并不难,即使您表中的信息似乎也没有正确存储:

SELECT  ClassID
       ,(SELECT SUBSTRING((SELECT ',' + Name FROM @TableOne WHERE Students LIKE '%'+CAST(StudentID AS NVARCHAR(5))+'%' ORDER BY Name FOR XML PATH('')),2,200) AS CSV)
FROM @TableTwo 

您可以使用此代码(复制/粘贴)作为工作示例:

DECLARE @TableOne TABLE
(
    StudentID INT,
    Name NVARCHAR(100)
)

DECLARE @TableTwo TABLE
(
    ClassID INT,
    Students NVARCHAR(100)
)

INSERT INTO @TableOne (StudentID,Name)
VALUES  (1,'Mary')
       ,(2,'John')
       ,(3,'Peter')
       ,(4,'Edwards')
       ,(5,'Pepe')
       ,(6,'C.Ronaldo')
       ,(7,'Zidane')
       ,(8,'Raul')

INSERT INTO @TableTwo (ClassID,Students)
VALUES  (1,'1,3,5,6,8')
       ,(2,'2,4,7')


SELECT  ClassID
       ,(SELECT SUBSTRING((SELECT ',' + Name FROM @TableOne WHERE Students LIKE '%'+CAST(StudentID AS NVARCHAR(5))+'%' ORDER BY Name FOR XML PATH('')),2,200) AS CSV)
FROM @TableTwo 
于 2012-09-07T15:27:06.503 回答
2

我强烈建议您更改将 StudentID 存储在第二个表中的方式

你可以这样做:

ClassID      StudentIDs
    --------    -----------
      1          1
      1          2
      2          3
      2          4

然后我们可以使用查询来获取输出

SELECT ClassID , Names= 
    STUFF((SELECT ', ' + Names
           FROM Studentb 
           WHERE b.ClassID      = a.ClassID      
          FOR XML PATH('')), 1, 2, '')
FROM Studenta
GROUP BY ClassID      
于 2012-09-07T12:50:39.837 回答
2

为此,您需要创建一个 SQL 函数。

Create Procedure GetStudent
as
  select ClassID , dbo.fnGetNamesById(StudentIDs) 
  from Table2
go

 create function fnGetNamesById (@psCSString as varchar(500))
  returns varchar(max)    
  as
Begin
    DECLARE @otTemp TABLE(sID VARCHAR(20))
    DECLARE @sTemp VARCHAR(100)

 WHILE LEN(@psCSString) > 0
    BEGIN
      SET @sTemp = LEFT(@psCSString, ISNULL(NULLIF(CHARINDEX(',', @psCSString) - 1, -1),
                        LEN(@psCSString)))
      SET @psCSString = SUBSTRING(@psCSString,ISNULL(NULLIF(CHARINDEX(',', @psCSString), 0),
                                   LEN(@psCSString)) + 1, LEN(@psCSString))
      INSERT INTO @otTemp VALUES (ltrim(@sTemp))
    End
    set @sTemp = ''
    select @sTemp = @sTemp + Name from table1 where StudentID    in (select sID from @otTemp)

    return @sTemp
End
于 2012-09-07T13:21:26.877 回答