Total Pageviews

Wednesday, February 6, 2013

Reading xml node elements in SQL Server

Consider the given data is available in Configuration table with column names KeyName and Value, as shown below:

Now if you want to read the data for Period and LastDate node available in Value column, use the query mentioned below:
==================================================================


SELECT Value.value (' (/config/lastDate)[1]','Datetime') LastDate,
Value.value (' (/config/period)[1]','int')Period
FROM Configuration

==================================================================


The output will be:


If you want to update any element value in the XML nodes then use the following query:
==================================================================
SET @LastDate=?
UPDATE Configuration
SET Value.modify('
  replace value of (/config/lastDate/text())[1]
  with sql:variable("@LastDate") ')
where KeyName='Key_name'

==================================================================


The same query can be written without using variable as well.

No comments:

Post a Comment