在SQL Server中解析列值

huangapple go评论63阅读模式
英文:

Parse column value in SQL Server

问题

这个字符串在一个列中:

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

转化为:

Item ID value

1 1
2 6
4 8

英文:

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

&lt;item id=&quot;1&quot; value=&quot;1&quot;&gt;&lt;item id=&quot;2&quot; value=&quot;6&quot;&gt;&lt;item id=&quot;4&quot; value=&quot;8&quot;&gt;

into

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

答案1

得分: 2

你的数据类似于 XML 片段,并且它不是格式良好的。

你所需要做的就是动态生成 XML。之后,XQuery 就变得非常容易(正如 @Larnu 已经指出的)。不需要解析任何东西。

SQL

-- DDL 和示例数据填充,开始
DECLARE @tbl TABLE (ID INT IDENTITY PRIMARY KEY, tokens NVARCHAR(MAX));
INSERT @tbl (tokens) VALUES
(N'&lt;item id="1" value="1"&gt;&lt;item id="2" value="6"&gt;&lt;item id="4" value="8"&gt;');
-- DDL 和示例数据填充,结束

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

输出

id value
1 1
2 6
4 8
英文:

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&#39;&lt;item id=&quot;1&quot; value=&quot;1&quot;&gt;&lt;item id=&quot;2&quot; value=&quot;6&quot;&gt;&lt;item id=&quot;4&quot; value=&quot;8&quot;&gt;&#39;);
-- DDL and sample data population, end

SELECT c.value(&#39;@id&#39;, &#39;INT&#39;) AS id
	, c.value(&#39;@value&#39;, &#39;INT&#39;) AS [value]
FROM @tbl t
CROSS APPLY (SELECT TRY_CAST(&#39;&lt;root&gt;&#39; + 
    REPLACE(tokens, &#39;&gt;&#39;, &#39;/&gt;&#39;) + 
    &#39;&lt;/root&gt;&#39; AS XML)) AS t1(x)
CROSS APPLY x.nodes(&#39;/root/item&#39;) AS t2(c);

Output

id value
1 1
2 6
4 8

huangapple
  • 本文由 发表于 2023年2月24日 01:44:04
  • 转载请务必保留本文链接:https://go.coder-hub.com/75548455.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定