使用sql将字符串拆分为不同的列

时间:2017-05-03 17:48:19

标签: sql sql-server sql-server-2008

如何将列中的特定字符串拆分为三个不同的列

样品:

Column_A
----------
{"nationalCode":"1234567893","username":"123","ip":"::1"}
{"nationalCode":"1234567892","username":"test","ip":"172.30.10.11"}
{"nationalCode":"1234567890"}
{"nationalCode":"1234567891","username":"test"}

应该是

nationalcode|username|Ip
---------------------------
1234567893  |123     |::1 
1234567892  |test    |172.30.10.11
1234567890  |null    |null
1234567891  |test    |null
到目前为止我刚刚尝试过的其中一个领域是(我不知道如何解决它)

 select  SUBSTRING(REPLACE(SUBSTRING(ActionInput,CHARINDEX('nationalCode',ActionInput)+len('nationalCode":"'),CHARINDEX(',',ActionInput)),'""',''),0,11) as national1,
         REPLACE(SUBSTRING(ActionInput,CHARINDEX('username',ActionInput)+len('username":"'),CHARINDEX(',',ActionInput)),'"}','') as a

        from LogTBL

1 个答案:

答案 0 :(得分:2)

在这种情况下,您可以使用ReplaceColumn_A更改为XML并按VALUE()

获取预期数据
DECLARE @SampleData AS TABLE
(
    Column_A varchar(max)
)

INSERT INTO @SampleData
VALUES 
('{"nationalCode":"1234567893","username":"123","ip":"::1"}'),
('{"nationalCode":"1234567892","username":"test","ip":"172.30.10.11"}'),
('{"nationalCode":"1234567890"}'),
('{"nationalCode":"1234567891","username":"test"}')

;WITH temp AS
(
    SELECT CAST(REPLACE(replace(replace(replace(sd.Column_A, '":"', '="'),
                    '{"', '<x '),'}','></x>' ), '","','" ') AS xml) AS XmlValue
    FROM @SampleData sd
)
SELECT  t.XmlValue.value('(/x/@nationalCode)[1]', 'varchar(30)') AS nationalCode,
        t.XmlValue.value('(/x/@username)[1]', 'varchar(30)') AS username,
        t.XmlValue.value('(/x/@ip)[1]', 'varchar(30)') AS ip
FROM temp t

演示链接:http://rextester.com/YEPUI94059