My SQL Server 2008 database table has a XML field. I would like to select nodes from the field, along with other fields. For example, consider the following table:
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>'
I want the result be:
001 | Ross | Geller
002 | Rachel | Green
Is that possible? Thanks,
This should do it:
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 )
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With