這裏是它採用了Numbers表格,XML和CROSS APPLY(兩次),非UDF的解決方案:
DECLARE @Numbers TABLE (Num INT);
INSERT INTO @Numbers VALUES (1);
INSERT INTO @Numbers VALUES (2);
INSERT INTO @Numbers VALUES (3);
INSERT INTO @Numbers VALUES (4);
INSERT INTO @Numbers VALUES (5);
INSERT INTO @Numbers VALUES (6);
INSERT INTO @Numbers VALUES (7);
INSERT INTO @Numbers VALUES (8);
INSERT INTO @Numbers VALUES (9);
DECLARE @Results TABLE (StateAbbrevs VARCHAR(255), NumOfResults INT);
INSERT INTO @Results VALUES ('MD', 5);
INSERT INTO @Results VALUES ('VA', 2);
INSERT INTO @Results VALUES ('DC', 7);
INSERT INTO @Results VALUES ('MD|VA', 2);
INSERT INTO @Results VALUES ('CA|NY|VA', 1);
DECLARE @Abbrev TABLE (StateAbbrev VARCHAR(2), StateName VARCHAR(255));
INSERT INTO @Abbrev VALUES ('MD', 'Maryland');
INSERT INTO @Abbrev VALUES ('VA', 'Virginia');
INSERT INTO @Abbrev VALUES ('DC', 'District of Columbia');
INSERT INTO @Abbrev VALUES ('CA', 'California');
INSERT INTO @Abbrev VALUES ('NY', 'New York');
--SELECT * FROM @Results;
--
--SELECT * FROM @Abbrev;
SELECT STUFF(StateNames, 1, 1, '') AS StateNames,
NumOfResults
FROM @Results AS RESULTS0
CROSS APPLY (SELECT ',' + ABBREV.StateName
FROM (SELECT PVT.StateAbbrev,
RESULTS.StateAbbrevs
FROM @Results AS RESULTS
CROSS APPLY (SELECT SUBSTRING(RESULTS.StateAbbrevs, NUMBERS.Num, CHARINDEX('|', RESULTS.StateAbbrevs + '|', NUMBERS.Num) - NUMBERS.Num) AS StateAbbrev
FROM @Numbers AS NUMBERS
WHERE NUMBERS.Num <= LEN(RESULTS.StateAbbrevs)
AND SUBSTRING('|' + RESULTS.StateAbbrevs, NUMBERS.Num, 1) = '|'
) AS PVT
) AS X
LEFT JOIN @Abbrev AS ABBREV ON ABBREV.StateAbbrev = X.StateAbbrev
WHERE StateAbbrevs = RESULTS0.StateAbbrevs
FOR
XML PATH('')
) AS Y (StateNames)
這是一個常見的問題,只是代替 '管' 逗號'。我會谷歌和搜索堆棧溢出像'sql split逗號'。 – 2009-10-30 20:56:07
這不是真的一樣,我熟悉如何分割值,或生成一個逗號分隔列表。在這種情況下,我正在尋找用實際值替換ID。到目前爲止,我想不出一種不涉及編寫函數的方式。 – PBG 2009-10-30 21:04:21