Friday, May 25, 2012

Value method in sqlserver with xml datatype

When datatype in sqlserver for any column is choosed xml or if there is any column in database with data of xml type. And your requirement is to display the normal text on page after fetching data from xml data, at that time value method comes into play.
Following are few examples that I recently used:
Eg.1:
<![CDATA[test@test.com]]>
I have data in a column in following format:
 
and we want to fetch only "test@test.com", then I have used value method in following way:
select cast(columnName as xml).value('.',varchar(max)) from table name.



It is working perfectly.
Eg 2.
SELECT CatalogDescription.value('           
    declare namespace PD="http://schemas.microsoft.com/sqlserver
/2004/07/adventure-works/ProductModelDescription";           
       (/PD:ProductDescription/@ProductModelID)[1]', 'int')
 AS Result           
FROM Production.ProductModel           
WHERE CatalogDescription IS NOT NULL           
ORDER BY Result desc 
 
output 
35
34