簡單的方法是通過將表A [代碼] column data(csv) into separate rows.
然後與表B加入,以獲得各自的代碼。最後convert the rows to CSV
得到結果。嘗試這個。
CREATE TABLE #tablea
([ID] INT,[Codes] VARCHAR(100))
INSERT INTO #tablea
VALUES (1,'A;B'),(2,'D'),(3,'A;C')
CREATE TABLE #tableB
([ID] VARCHAR(100),[Codes] VARCHAR(100))
INSERT INTO #tableb
VALUES ('A','Apple'),('B','Orange'),
('C','Pear'),('D','Strawberry')
SELECT a.id,
a.Codes old_code,
b.Codes Parsed_Codes
INTO #final
FROM #tableb b
JOIN (SELECT id,
codes,
Split.a.value('.', 'VARCHAR(100)') [new_Codes]
FROM (SELECT id,
[Codes],
Cast ('<M>' + Replace([Codes], ';', '</M><M>')
+ '</M>' AS XML) AS Data
FROM #tablea) AS A
CROSS APPLY Data.nodes ('/M') AS Split(a)) a
ON a.new_Codes = b.id
SELECT t1.ID,
old_code,
Stuff((SELECT '; ' + CONVERT(VARCHAR, Parsed_Codes)
FROM #final b
WHERE b.ID = t1.ID
FOR XML PATH('')), 1, 2, '')
FROM #final t1
GROUP BY t1.id,
old_code
OUTPUT
ID old_code Parsed_Codes
-- -------- ------------
1 A;B Apple; Orange
2 D Strawberry
3 A;C Apple; Pear
(注:臨時表,可避免爲了避免混淆代碼我用臨時表)
由於普拉迪普。像魅力一樣工作! – 2014-10-30 10:32:48