Wednesday, 27 August 2014

Pass XML parameter to Stored Procedure

Pass XML parameter to Stored Procedure
The Stored Procedure for parsing XML data
The below stored procedure is accepting a parameter of type XML (which would be passed from the code behind). This XML object is parsed and the Attribute and Tag values are fetched and inserted into the Table.
The nodes function of the XML data type is uses XQuery expression to pull out the XML nodes from the XML, for this case I need to fetch the Customer nodes and hence the expression is i.e. /Customers/Customer where Customers is the Root Node and Customer is the child node.
Once the nodes are fetched we need to extract the attribute and tag Inner Text values. For fetching the Inner Text values between the Tags we need to make use of the values function.
The values function can read the Attribute as well as the Inner Text.
Attribute
In order to read the attribute we need to pass the name of the Attribute prefix with @ and its data type, in this example the attribute Id is fetched using Customer.value('@Id', 'INT').
Inner Text
In order to fetch the inner text we need to pass the name of the Tag and its data type. The Inner Text of the XML tag is fetched using text function and we also make use of an index [1] which means it should fetch only the first matched value.
Finally the values are inserted into the CustomerDetails table.

CREATE PROCEDURE [dbo].[InsertXML]
@xml XML
AS
BEGIN
      SET NOCOUNT ON;

      INSERT INTO CustomerDetails
      SELECT
      Customer.value('@Id','INT') AS Id, --ATTRIBUTE
      Customer.value('(Name/text())[1]','VARCHAR(100)') AS Name, --TAG
      Customer.value('(Country/text())[1]','VARCHAR(100)') AS Country --TAG
      FROM
      @xml.nodes('/Customers/Customer')AS TEMPTABLE(Customer)
END