在SQL Server 2005以後,您可以使用XML Path()來連接值。它看起來也非常高效。
編輯:進行了測試以下和工作
SELECT
t1.memberid,
t1.[name],
ISNULL(STUFF(
(
SELECT
', ' + t2.interestName
FROM
table2 t2
INNER JOIN
table3 t3
ON
t2.interestId = t3.interestId
WHERE
t3.memberid = t1.memberid
FOR XML PATH('')
), 1, 2, ''
), 'None') As interests
FROM
table1 t1
GROUP BY
t1.memberid,
t1.[name]
示例代碼:
DECLARE @table1 TABLE (memberid INT IDENTITY(1,1), name VARCHAR(25))
INSERT INTO @table1 VALUES('dennis');
INSERT INTO @table1 VALUES('mary');
INSERT INTO @table1 VALUES('bill');
DECLARE @table2 TABLE (interestId INT IDENTITY(1,1), interestName VARCHAR(25))
INSERT INTO @table2 VALUES('play basketball');
INSERT INTO @table2 VALUES('music');
INSERT INTO @table2 VALUES('movie');
INSERT INTO @table2 VALUES('play hockey');
INSERT INTO @table2 VALUES('wine tasting');
INSERT INTO @table2 VALUES('cheese rolling');
DECLARE @table3 TABLE (memberid INT, interestId INT)
INSERT INTO @table3 VALUES(1,1);
INSERT INTO @table3 VALUES(1,2);
INSERT INTO @table3 VALUES(1,3);
INSERT INTO @table3 VALUES(2,2);
INSERT INTO @table3 VALUES(2,4);
INSERT INTO @table3 VALUES(2,6);
INSERT INTO @table3 VALUES(3,1);
INSERT INTO @table3 VALUES(3,5);
INSERT INTO @table3 VALUES(3,6);
SELECT
t1.memberid,
t1.[name],
ISNULL(STUFF(
(
SELECT
', ' + t2.interestName
FROM
@table2 t2
INNER JOIN
@table3 t3
ON
t2.interestId = t3.interestId
WHERE
t3.memberid = t1.memberid
FOR XML PATH('')
), 1, 2, ''
), 'None') As interests
FROM
@table1 t1
GROUP BY
t1.memberid,
t1.[name]
結果
memberid name interests
----------- -----------------------------------------------------------------------
1 dennis play basketball, music, movie
2 mary music, play hockey, cheese rolling
3 bill play basketball, wine tasting, cheese rolling
什麼RDBMS? SQL Server 2000,2005,MySQL等 – 2009-08-02 10:32:49
SQL Server 2005 – MemoryLeak 2009-08-02 11:23:56