如何将列中的特定字符串拆分为三个不同的列
样品:
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
答案 0 :(得分:2)
在这种情况下,您可以使用Replace
将Column_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