简体   繁体   中英

Convert XML in a column to a table

My input is an XML column in SQL Server table like this:

<word Entry="Ketab" Affix="miyanvand" Pos="esm" Derv="Jamed" />

Desired output: a table like this:

Entry    | Affix       | Pos     | Derv
Ketab    | miyanvand   | esm     | Jamed

If you are using sql-server 2005+. Then maybe something like this:

DECLARE @xml XML=
'<word Entry="Ketab" Affix="miyanvand" Pos="esm" Derv="Jamed" />'

SELECT 
   Y.ID.value('(@Entry)[1]', 'Varchar(100)') as [Entry],
   Y.ID.value('(@Affix)[1]', 'Varchar(100)') as [Affix],
   Y.ID.value('(@Pos)[1]', 'Varchar(100)') as [Pos],
   Y.ID.value('(@Derv)[1]', 'Varchar(100)') as [Derv]
FROM @xml.nodes('/word') as Y(ID)

Or you can also do it like this:

DECLARE @xml XML=
'<word Entry="Ketab" Affix="miyanvand" Pos="esm" Derv="Jamed" />'

SELECT 
    @xml.value('(/word/@Entry)[1]', 'varchar(50)') as Entry,
    @xml.value('(/word/@Affix)[1]', 'varchar(50)') as Affix,
    @xml.value('(/word/@Pos)[1]', 'varchar(50)') as Pos,
    @xml.value('(/word/@Derv)[1]', 'varchar(50)') as Derv

Or if you have a table. Then something like this:

DECLARE @tbl TABLE(ID INT,someXML XML)
INSERT INTO @tbl
VALUES
    (1,'<word Entry="Ketab" Affix="miyanvand" Pos="esm" Derv="Jamed" />')

SELECT
    tbl.ID,
    Y.ID.value('(@Entry)[1]', 'Varchar(100)') as [Entry],
    Y.ID.value('(@Affix)[1]', 'Varchar(100)') as [Affix],
    Y.ID.value('(@Pos)[1]', 'Varchar(100)') as [Pos],
    Y.ID.value('(@Derv)[1]', 'Varchar(100)') as [Derv]
FROM
    @tbl AS tbl
    CROSS APPLY someXML.nodes('/word') as Y(ID)

You can use the value function on the XML column:

declare @t table (col1 xml)
insert @t values ('<word Entry="Ketab" Affix="miyanvand" />')

select  t.col1.value('(/word/@Entry)[1]', 'varchar(50)') as Entry
,       t.col1.value('(/word/@Affix)[1]', 'varchar(50)') as Affix
from    @t t

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM