Database Simplified Headline Animator

Database Simplified

Thursday 2 June 2011

Use of XML DataType | How to Insert or Update multiple Rows From GridView to Stored Procedure


How to Insert All the Rows From Following GridView To Database Table.

If you see, Generally we find most of the people writing For or While Loops and multiple iterations to Insert Rows Into Database.

The above Approach causes Multiple Hits to database which may degrade the performance of database.

Let see how XML Datatype can Help us in Optimizing this task.



Write a For loop to Generate String As Following



<productname>Alice Mutton</productname>



If you See Its Simple HTML with Opening and closing tags. Just Loop it and you  will have Following String.

Each row should have Opening <Table> and closing </Table> Tags with  Opening and Closing Field Tags.

string mystr=string.Empty;


<productid>17</productid><productname>Alice Mutton</productname>




<productid>3</productid><productname>Aniseed Syrup</productname>




<productid>40</productid><productname>Boston Crab Mutton</productname>




<productid>60</productid><productname>Camembert Pierrot</productname>




<productid>18</productid><productname>Carnarvon Tigers</productname>



Now You can Pass this String as XML Parameter To Stored Procedure Which Executes Following Query To Extract Result From XML Parameter.

Declare @xmlData Xml;

Set @xmlData=mystr;   -- Assigning XML String to XML DataType


How to Read Data From Xml Variable

Note : Field name as Case Sensitive and DataType Should Match.

Select'productid[1]','int') as ProductId,'productname[1]','varchar(50)') as ProductName,'unitprice[1]','decimal(12,4)') as UnitPrice
From @xmlData.nodes('/table') as x(data)




Note :  As Xml Doesn’t Support Following Symbols

& , < , >

We Need Replace These Symbols In XmlString Before Passing string Value to Store Procedure Parameter  or XMLVariable.

With Following Characters

&  --  &amp;

<  --   &lt;

>  --  &gt;

the Output of Query can be Used To Update and Insert Data In a Table



Hot smile

No comments:

Post a Comment