我的SQL Server 2008数据库表有一个XML字段。我想从字段中选择节点以及其他字段。例如,请考虑下表:
DECLARE @TestTable AS TABLE ([Id] VARCHAR(20), [Name] XML )
INSERT INTO @TestTable SELECT
'001',
'<Name><First>Ross</First><Last>Geller</Last></Name>'
UNION ALL SELECT
'002',
'<Name><First>Rachel</First><Last>Green</Last></Name>'
我希望结果为:
001 | Ross | Geller
002 | Rachel | Green
这可能吗?谢谢,
答案 0 :(得分:8)
这应该这样做:
DECLARE @TestTable AS TABLE (
[Id] VARCHAR(20),
[Name] XML
)
INSERT INTO @TestTable
SELECT '001',
'<Name><First>Ross</First><Last>Geller</Last></Name>'
UNION ALL
SELECT '002',
'<Name><First>Rachel</First><Last>Green</Last></Name>'
SELECT Id,
x.value('(/Name/First)[1]', 'varchar(20)') AS [First],
x.value('(/Name/Last)[1]', 'varchar(20)') AS [Last]
FROM @TestTable t
CROSS APPLY [Name].nodes('/Name') AS tbl ( x )