我有以下XML:
<help>
<item field="field1" help="helptext" />
<item field="field2" help="helptext" />
<item field="field3" help="helptext" />
</help>
我将它存储在SQL服务器中的XML DataType中,并希望单独提取字段和帮助文本。即结果集类似于:
| field1 | helptext |
| field2 | helptext |
| field3 | helptext |
有人知道如何实现这个目标吗?
Kindest Regards,
亚当
答案 0 :(得分:1)
看看以下是否有帮助:
DECLARE @processedXmlDoc int
DECLARE @inputDoc varchar(1000)
EXEC sp_xml_preparedocument @processedXmlDoc OUTPUT, @inputDoc
SELECT *
FROM OPENXML (@processedXmlDoc , '/help/item',1)
WITH (field varchar(20) 'field',
help varchar(20) 'helpText')
EXECUTE sp_xml_removedocument @idoc
希望有所帮助。
答案 1 :(得分:1)
尝试这样的事情:
DECLARE @input XML = '<help>
<item field="field1" help="helptext" />
<item field="field2" help="helptext" />
<item field="field3" help="helptext" />
</help>'
SELECT
Field = Item.value('@field', 'varchar(25)'),
HELP = Item.value('@help', 'varchar(50)')
FROM
@input.nodes('/help/item') AS XTbl(Item)
答案 2 :(得分:1)
DECLARE @xml AS XML = '<help>
<item field="field1" help="helptext" />
<item field="field2" help="helptext" />
<item field="field3" help="helptext" />
</help>'
select c.value('@field', 'varchar(max)') field, c.value('@help', 'varchar(max)') help
from @xml.nodes('/help/item') T(c);
要在xml数据在表字段中时实现相同的目的,请使用:
SELECT c.value('@field', 'varchar(max)') field, c.value('@help', 'varchar(max)') help
FROM MyTable A CROSS APPLY A.MyXmlField.nodes('/help/item') T(c)
其中MyTable是包含xml数据的字段MyXmlField的表。