对标题感到抱歉,但这个问题难以理解。我正在处理一个构造不良的数据库,并遇到了一个在同一列上有多个记录的表,如下所示:
| Column Header |
Record1; Record2; Record3
我想询问SQL中是否有任何方法可以使用;
作为分隔符来分隔这些记录。我问这个是因为重建数据库目前不是一种选择。
答案 0 :(得分:1)
快速解决方案 -
DECLARE @T TABLE
(
Col NVARCHAR(2000),
Col1 AS PARSENAME(REPLACE(Col, '; ', '.'), 3),
Col2 AS PARSENAME(REPLACE(Col, '; ', '.'), 2),
Col3 AS PARSENAME(REPLACE(Col, '; ', '.'), 1)
)
INSERT INTO @T (Col)
VALUES ('Record1; Record2; Record3')
SELECT * FROM @T
良好的解决方案 - 规范化表
答案 1 :(得分:1)
DECLARE @badData TABLE (id INT NOT NULL, txt NVARCHAR(max));
INSERT INTO @badData
VALUES (1, 'foo,bar,baz'), (2, NULL);;
-- the idea is to recursively 'pop' a value from the start of the string, splitting it into 'head' and 'tail' components
WITH unpacked (id, head, tail)
AS (
SELECT id, LEFT(txt, CHARINDEX(',', txt + ',') - 1), STUFF(txt, 1, CHARINDEX(',', txt + ','), '')
FROM @badData
UNION ALL
SELECT id, LEFT(tail, CHARINDEX(',', TAIL + ',') - 1), STUFF(tail, 1, CHARINDEX(',', tail+ ','), '')
FROM unpacked
WHERE tail > ''
)
SELECT id, head
FROM unpacked
ORDER BY id