解决方案并不难,即使您表中的信息似乎也没有正确存储:
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