Monday, February 11, 2013

Querying XML datatype using T-SQL

--- Extract Strings from XML data type using T-SQL ---

---- Fetch value in XML Node format ----

DECLARE @xmlstring XML
SELECT @xmlstring =
'<Employee>
  <name>Kalyan Kumar</name>
  <city>Hyderabad</city>
  <state>Andhra Pradesh</state>
  <email>kalyan@yahoo.com</email>
</Employee>'
SELECT @xmlstring.query('(/Employee/name)')  AS Emp_Name
SELECT @xmlstring.query('/Employee/name/text()')  AS Emp_Name

---- Fetch value in String format ----
DECLARE @xmlstring XML
SELECT @xmlstring =
'<Employee>
  <name>Kalyan Kumar</name>
  <city>Hyderabad</city>
  <state>Andhra Pradesh</state>
  <email>kalyan@yahoo.com</email>
</Employee>'
SELECT @xmlstring.value('(/Employee/name)[1]', 'CHAR(30)')  AS Emp_Name

---- Fetch value from XML Sub Node in string format----
DECLARE @xmlstring XML
SELECT @xmlstring =
'<Employee>
  <Details name="Kalyan Kumar">
  <city>Hyderabad</city>
  <state>Andhra Pradesh</state>
  <email>kalyan@yahoo.com</email>
  </Details>
  </Employee>'
SELECT @xmlstring.value('(//Details/@name)[1]','char(30)')
SELECT @xmlstring.value('(/Employee/Details/city)[1]', 'CHAR(30)')

No comments: