我从消息表中获得了以下column(name-xml)值(XML格式)
<Line>
<ID>12345</ID>
<ErrorText>sky is red</ErrorText>
</Line>
<Line>
<ID>54321</ID>
<ErrorText>roses are white</ErrorText>
</Line>
<Line>
<ID>98765</ID>
<ErrorText>Sun rises in the east</ErrorText>
</Line>
从这里我需要以下数据
ID ErrorText
12345 sky is red
54321 roses are white
98765 Sun rises in the east
我需要从同一数据库表列中分离出2个单独的列。
答案 0 :(得分:1)
尝试一下
DECLARE @mockup TABLE(ID INT IDENTITY, YourXmlColumn XML);
INSERT INTO @mockup VALUES
(
N'<Line><ID>12345</ID><ErrorText>sky is red</ErrorText></Line><Line><ID>54321</ID><ErrorText>roses are white</ErrorText></Line><Line><ID>98765</ID><ErrorText>Sun rises in the east</ErrorText></Line>'
);
SELECT ln.value('(ID/text())[1]','int') AS ID
,ln.value('(ErrorText/text())[1]','nvarchar(max)') AS ID
FROM @mockup m
CROSS APPLY m.YourXmlColumn.nodes('/Line') A(ln);
CROSS APPLY
允许您调用本地XML.method .nodes()
。 XPath
“ / Line”将每个重复的<Line>
元素作为单独的行返回。方法.value()
使您可以选择元素的内容。
如何转换不推荐使用的TEXT
类型的示例。我使用CTE进行投射。
WITH casted AS
(
SELECT t.*
,CAST(CAST(t.YourXmlColumn AS VARCHAR(MAX)) AS XML) AS ToXml
FROM YourTable t
--WHERE... (filters go here)
)
SELECT ln.value('(ID/text())[1]','int') AS ID
,ln.value('(ErrorText/text())[1]','nvarchar(max)') AS ID
FROM casted
CROSS APPLY casted.ToXml.nodes('/Line') A(ln);
答案 1 :(得分:0)
尝试:
DECLARE @XML XML = '
<Line>
<ID>12345</ID>
<ErrorText>sky is red</ErrorText>
</Line>
<Line>
<ID>54321</ID>
<ErrorText>roses are white</ErrorText>
</Line>
<Line>
<ID>98765</ID>
<ErrorText>Sun rises in the east</ErrorText>
</Line>'
SELECT
Tbl.Col.value('ID[1]', 'INT') ID
,Tbl.Col.value('ErrorText[1]', 'VARCHAR(100)') ErrorText
FROM
@XML.nodes('//Line') Tbl(Col)