h1

How to Read values from XML Variable/Columns with SQL SERVER 2005

12/23/2008

Read Attributes value from XML variable:

DECLARE @xml XML
SELECT @xml = 
'<TejasShah>
  <Att ID="Tejas" Text="TejasShah" />
  <Att ID="Tejas2" Text="TejasShah2" />
  <Att ID="Tejas3" Text="TejasShah3" />
</TejasShah>'

SELECT  x.v.value('@ID[1]', 'VARCHAR(100)') AS [ID],
        x.v.value('@Text[1]', 'VARCHAR(100)') AS [Text]
FROM    @xml.nodes('/TejasShah/Att') x(v)

Output will be:

Read values from xml variable

In other way, we can  also get value from ELEMENTS of xml variable. Lets see:

DECLARE @xml XML
SELECT @xml = '
<TejasShah>
  <Att>
    <ID>Tejas</ID>
    <Text>TejasShah</Text>
  </Att>
  <Att>
    <ID>Tejas2</ID>
    <Text>TejasShah2</Text>
  </Att>
  <Att>
    <ID>Tejas3</ID>
    <Text>TejasShah3</Text>
  </Att>
</TejasShah>'
SELECT  x.v.value('ID[1]', 'VARCHAR(100)'),
        x.v.value('Text[1]', 'VARCHAR(100)')
FROM    @xml.nodes('/TejasShah/Att') x(v)

Output will be the same as above:

Read values from XML Elements

Advertisements

4 comments

  1. how to use this with table if we have same structure but this xml is in a xml column.


  2. Hi,

    You can do it by have this query in LOOP and process one by one record.

    Thanks,
    Tejas
    SQLYoga.com


  3. Thanks for the help.


  4. SELECT x.v.value(‘(@ID)[1]’, ‘varchar(50)’,
    x.v.value(‘(@Text)[1]’, ‘VARCHAR(100)’)
    FROM tblxml
    –WHERE CONDITION if required
    CROSS APPLY tblxmlcolumnname.nodes(‘TejasShah/Att’) x(v)

    I haven’t tested the query yet. but try it out.



Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: