Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Select XML nodes using TSQL

Tags:

tsql

xml

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,

like image 297
Xi 张熹 Avatar asked Apr 26 '11 21:04

Xi 张熹


1 Answers

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 )
like image 97
Ben Thul Avatar answered Sep 28 '22 15:09

Ben Thul