我想将文件路径分成不同的列。以下代码适用于大多数情况,但它不适用于下面的示例案例。在有重复词的情况下似乎不起作用。示例代码最多有三列,但由于某些文件路径较长,因此会重复。使用SQL Sever 2008。
我有数千行,如:
Garden Center|Seeds|Flower Seeds|Organic Flower Seeds
期望的输出:
Path1
Garden Center
Path2
Seeds
Path3
Flower Seeds
Path4
Organic Flower Seeds
目前我正在:
Path1
Garden Center
Path2
Seeds
Path3
Flower Organic Flower Seeds
- 代码:
DROP TABLE #TEMP1
DROP TABLE #TEMP2
DROP TABLE #TEMP3
SELECT
ID_Ref,
CollectionPath,
CollectionPath AS Path_a,
CollectionPath AS Path_1,
CollectionPath AS Path_b,
CollectionPath AS Path_2,
CollectionPath AS Path_c,
CollectionPath AS Path_3
INTO #TEMP1
FROM DATA
UPDATE #TEMP1
SET Path_a = (
CASE WHEN CHARINDEX('|',CollectionPath) > 0 THEN
REPLACE(CollectionPath,LEFT(CollectionPath+'|', CHARINDEX('|',CollectionPath+'|')),'')
ELSE
NULL
END
)
UPDATE #TEMP1
SET Path_1 = (
CASE WHEN CHARINDEX('|',Path_a) > 0 THEN
SUBSTRING(Path_a,1,CHARINDEX('|',Path_a)-1)
ELSE
NULL
END
)
UPDATE #TEMP1
SET Path_b = (
CASE WHEN CHARINDEX('|',Path_a) > 0 THEN
REPLACE(Path_a,LEFT(Path_a+'|', CHARINDEX('|',Path_a+'|')),'')
ELSE
NULL
END
)
UPDATE #TEMP1
SET Path_2 = (
CASE WHEN CHARINDEX('|',Path_b) > 0 THEN
SUBSTRING(Path_b,1,CHARINDEX('|',Path_b)-1)
ELSE(
CASE WHEN Path_b IS NOT NULL THEN Path_b
ELSE NULL
END
)
END
)
UPDATE #TEMP1
SET Path_c = (
CASE WHEN CHARINDEX('|',Path_b) > 0 THEN
REPLACE(Path_b,LEFT(Path_b+'|', CHARINDEX('|',Path_b+'|')),'')
ELSE
NULL
END
)
UPDATE #TEMP1
SET Path_3 = (
CASE WHEN CHARINDEX('|',Path_c) > 0 THEN
SUBSTRING(Path_c,1,CHARINDEX('|',Path_c)-1)
ELSE(
CASE WHEN Path_c IS NOT NULL THEN Path_c
ELSE NULL
END
)
END
)
SELECT ID_Ref, CollectionPath,
Path_a,
Path_1,
Path_b,
Path_2,
Path_c,
Path_3
INTO #TEMP2
FROM #TEMP1
SELECT SC.CollectionPath,
Path_a,
Path_1,
Path_b,
Path_2,
Path_c,
Path_3
INTO #TEMP3
FROM DATA SC
LEFT OUTER JOIN #TEMP2 ON SC.ID_Ref = #TEMP2.ID_Ref
SELECT *
FROM #TEMP3