Parse column value in SQL Server

u7up0aaq  于 2023-03-07  发布在  SQL Server
关注(0)|答案(1)|浏览(141)

I have a table with a Varchar column with the value as mentioned below. How can i parse this string into columns

This string in a column

<item id="1" value="1"><item id="2" value="6"><item id="4" value="8">

into

Item ID  value
--------------
1        1
2        6
4        8
fafcakar

fafcakar1#

Your data resembles XML fragment. And it is not well-formed.

All what you need is to compose XML on the fly. After that XQuery makes it very easy (as @Larnu pointed out it already). No need to parse anything.

SQL

-- DDL and sample data population, start
DECLARE @tbl TABLE (ID INT IDENTITY PRIMARY KEY, tokens NVARCHAR(MAX));
INSERT @tbl (tokens) VALUES
(N'<item id="1" value="1"><item id="2" value="6"><item id="4" value="8">');
-- DDL and sample data population, end

SELECT c.value('@id', 'INT') AS id
    , c.value('@value', 'INT') AS [value]
FROM @tbl t
CROSS APPLY (SELECT TRY_CAST('<root>' + 
    REPLACE(tokens, '>', '/>') + 
    '</root>' AS XML)) AS t1(x)
CROSS APPLY x.nodes('/root/item') AS t2(c);

Output

idvalue
11
26
48

相关问题