473,667 Members | 2,576 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

How to Bulk Update Using SQL Server XML

1 New Member
This Post is used to show how to bulk update records from grid view rather to updating one by one.

The concept : create a xml string(string will contain all the records to be updated with some separator ) from code behind and pass this string to stored procedure from where these records will be updated to appropriate table by reading data from XML data type variable and update will be done using temporary table concept.
I have used C# sample code for Example:


Table Structure:

CustId Int

CustName Varchar(50)

CustPosition Varchar(50)

CustCity Varchar(50)

CustState Varchar(50)

Grid:


First

The Grid View is designed as below.

Expand|Select|Wrap|Line Numbers
  1. <div>
  2. GridView ID=”gvCustomer” runat=”server” AutoGenerateColumns=”False” BackColor=”White”
  3.  
  4. BorderColor=”#999999″ BorderWidth=”1px” CellPadding=”3″ DataKeyNames=”CustID”
  5.  
  6. DataSourceID=”SqlDataSource1″ GridLines=”Vertical” BorderStyle=”None” ShowFooter=”True”>
  7.  
  8. <RowStyle BackColor=”#EEEEEE” ForeColor=”Black” />
  9.  
  10. <Columns>
  11.  
  12. <asp:BoundField DataField=”CustID” HeaderText=”CustID” InsertVisible=”False” ReadOnly=”True” SortExpression=”CustID” />
  13.  
  14. <asp:TemplateField HeaderText=”Name” SortExpression=”CustName”>
  15.  
  16. <ItemTemplate>
  17.  
  18. <asp:TextBox ID=”txtName” runat=”server” Text=’<%# Bind(“CustName”) %>’ BorderStyle=”Solid” BorderWidth=”1px”/>
  19.  
  20. </ItemTemplate>
  21.  
  22. </asp:TemplateField>
  23.  
  24. <asp:TemplateField HeaderText=”Position” SortExpression=”CustPosition”>
  25.  
  26. <ItemTemplate>
  27.  
  28. <asp:TextBox ID=”txtPosition” runat=”server” Text=’<%# Bind(“CustPosition”) %>’ BorderStyle=”Solid” BorderWidth=”1px”/>
  29.  
  30. </ItemTemplate>
  31.  
  32. </asp:TemplateField>
  33.  
  34. <asp:TemplateField HeaderText=”City” SortExpression=”CustCity”>
  35.  
  36. <ItemTemplate>
  37.  
  38. <asp:TextBox ID=”txtCity” runat=”server” Text=’<%# Bind(“CustCity”) %>’ BorderStyle=”Solid” BorderWidth=”1px”/>
  39.  
  40. </ItemTemplate>
  41.  
  42. </asp:TemplateField>
  43.  
  44. <asp:TemplateField HeaderText=”State” SortExpression=”CustState”>
  45.  
  46. <ItemTemplate>
  47.  
  48. <asp:TextBox ID=”txtState” runat=”server” Text=’<%# Bind(“CustState”) %>’ BorderStyle=”Solid” BorderWidth=”1px”/>
  49.  
  50. </ItemTemplate>
  51.  
  52. </asp:TemplateField>
  53.  
  54. </Columns>
  55.  
  56. <FooterStyle BackColor=”#CCCCCC” ForeColor=”Black” />
  57.  
  58. <PagerStyle BackColor=”#999999″ ForeColor=”Black” HorizontalAlign=”Center” />
  59.  
  60. <SelectedRowStyle BackColor=”#008A8C” ForeColor=”White” Font-Bold=”True” />
  61.  
  62. <HeaderStyle BackColor=”#000084″ Font-Bold=”True” ForeColor=”White” />
  63.  
  64. <AlternatingRowStyle BackColor=”#DCDCDC” />
  65.  
  66. </asp:GridView>
  67.  
  68. <asp:SqlDataSource ID=”SqlDataSource1″ runat=”server” ConnectionString=”data source=NSL-SEG089D\SQLEXPRESS;database=bankdb;Integrated Security=SSPI”
  69.  
  70. SelectCommand=”SELECT * FROM [Customer]“></asp:SqlDataSource>
  71.  
  72. <div align=”center” style=”width: 500px”>
  73.  
  74. <asp:Button ID=”btnUpdate” runat=”server” Text=”Update” OnClick=”btnUpdate_Click” />
  75.  
  76. <br />
  77.  
  78. <br />
  79.  
  80. <asp:Label ID=”lblError” runat=”server” Font-Bold=”True” ForeColor=”Black” Width=”544px”></asp:Label>
  81.  
  82. </div>
  83.  
  84. </div>
  85.  

Below is the OnClick event code of update button.

Expand|Select|Wrap|Line Numbers
  1.  
  2. createXml();
  3. string conStr = “data source=YOURDATASOURCE;database=DBNAME;Integrated Security=SSPI”;
  4. SqlConnection con = new SqlConnection(conStr);
  5. SqlCommand cmd = new SqlCommand(“UpdateCustomer”, con);
  6. cmd.CommandType = CommandType.StoredProcedure;
  7. cmd.Parameters.AddWithValue(“@XMLCustomer”, sb.ToString());
  8. try
  9. {
  10. using (con)
  11. {
  12. con.Open();
  13. cmd.ExecuteNonQuery();
  14. }
  15. lblError.Text = “Record(s) updated successfully”;
  16. lblError.ForeColor = System.Drawing.Color.Green;
  17. }
  18. catch (Exception ex)
  19. {
  20. lblError.Text = “Error Occured”;
  21. lblError.ForeColor = System.Drawing.Color.Red;
  22. }
  23. }
  24.  
  25.  

Function below is called on clicking of Update button to create a xml string of all the records to be updated.

Expand|Select|Wrap|Line Numbers
  1.  
  2. public void createXml()
  3. {
  4. sb.Append(“<root>”);
  5. for (int i = 0; i < gvCustomer.Rows.Count; i++)
  6. {
  7. string CustID = gvCustomer.Rows[i].Cells[0].Text;
  8. TextBox txtName = gvCustomer.Rows[i].FindControl(“txtName”) as TextBox;
  9. TextBox txtPosition = gvCustomer.Rows[i].FindControl(“txtPosition”) as TextBox;
  10. TextBox txtCity = gvCustomer.Rows[i].FindControl(“txtCity”) as TextBox;
  11. TextBox txtState = gvCustomer.Rows[i].FindControl(“txtState”) as TextBox;
  12. sb.Append(“<row CustID=’” + CustID + “‘ Name=’” + txtName.Text.Trim() + “‘ Position=’” + txtPosition.Text.Trim() +
  13. “‘ City=’” + txtCity.Text.Trim() + “‘ State=’” + txtState.Text.Trim() + “‘/>”);
  14. }
  15. sb.Append(“</root>”);
  16. }
  17.  
  18.  
Ultimately the Stored Procedure (updat Customer) used is as below

The parameter used in proc is an XML data type. Which will update customer table from temporary table created from XML.

Expand|Select|Wrap|Line Numbers
  1.  
  2. set ANSI_NULLS ON
  3.  
  4. set QUOTED_IDENTIFIER ON
  5.  
  6. go
  7.  
  8. ALTER PROCEDURE [dbo].[UpdateCustomer]
  9.  
  10. (
  11.  
  12. @XMLCustomer XML
  13.  
  14. )
  15.  
  16. AS
  17.  
  18. BEGIN
  19.  
  20. UPDATE Customer
  21.  
  22. SET CustName=TempCustomer.Item.value(‘@Name’, ‘VARCHAR(50)’),
  23.  
  24. CustPosition=TempCustomer.Item.value(‘@Position’, ‘VARCHAR(50)’),
  25.  
  26. CustCity=TempCustomer.Item.value(‘@City’, ‘VARCHAR(50)’),
  27.  
  28. CustState=TempCustomer.Item.value(‘@State’, ‘VARCHAR(50)’)
  29.  
  30. FROM @XMLCustomer.nodes(‘/root/row’) AS TempCustomer(Item)
  31.  
  32. WHERE CustID=TempCustomer.Item.value(‘@CustID’, ‘INT’)
  33.  
  34. RETURN 0
  35.  
  36. END
  37.  
  38.  
As you can see in screen shot below, I had update customer Name field with all surname prefix with first name. hope it will help you to bulk update the records.

Dec 13 '10 #1
0 8254

Sign in to post your reply or Sign up for a free account.

Similar topics

2
2205
by: Rob | last post by:
Hi, In the server explorer in Visual Studio.Net I'm able to design tables, create stored procedures, etc for the SQL 2000 database running locally on my computer. If I add a connection to a remove server on the network, I'm not able to do the above. Is there something that must be set in order to allow this. Thanks
3
7641
by: JP SIngh | last post by:
Hi All I have users who upload files using my application using ASPUPLOAD component. My code uploads the file to a network location and once the upload is finish I display the hyperlink using the following code <a href=\myserver\attachments\<%=server.urlencode(rs("FileName"))%> target="_blank" ><%=rs("Filename")%>
1
1339
by: Ali | last post by:
hi, I am new to asp.net. I have a question about Marshelling b/w client browser and web server(database). I heared that it is better to minimize going back and forth b/w client browser and the server.This will increase performance and improve scallability. With asp.net, using server controls. It seems every action at the client browser require a trip to the server, for instance, page_load ( to fill combo boxes), or the event of the combo...
2
2257
by: Stephen Brown | last post by:
We've been using dotNet for a couple of years now and have been updating our live server by just overwriting (Explorer drag and drop) the aspx and assembly files until we had some errors reported to us a couple of months ago that some clients received application server errors at the moment we updated (if I remember correctly, they were sharing or process in use errrors). Since then, we've been paranoid about ensuring that there is no...
4
3401
by: Jim Hammond | last post by:
It would be udeful to be able to get the current on-screen values from a FormView that is databound to an ObjectDataSource by using a callback instead of a postback. For example: public void RaiseCallbackEvent(string eventArgs) { // update the data object with the values currently on screen FormView1.UpdateItem(true); }
0
2797
by: Shawn Ferguson | last post by:
With the help of you, I've been able to successfully load my database with the contents of a "comma" delimited file. It loads about 5000 records in about 3 seconds:) Now I have another problem. The file I will be importing into SQL Server is serparated by "|" vertical bar opposed to "," comma. When I run my program with the comma separated text file, works great, but when I try to use the same process to import the | (vertical bar) it only...
1
6973
by: Rachel | last post by:
We recently upgraded to ASP.NET 2 AJAX Beta 2 an since we are encountering the following problem: STEPS: 1- navigate to a page containing a UpdatePanel using SERVER.TRANSFER 2- click on a button (regardless of type: button, linkButton, imageButton) 3- (first) async call works fine 4 - click again to make second async call and somehow the page path becomes
1
12005
by: tekedge | last post by:
Hi, I have to do an update using a query which uses CTE . Could any body please tell me how I can do an update. I am unable to update if I replace the final select with an update one. Thanks in advance Jay.
1
2156
oranoos3000
by: oranoos3000 | last post by:
hi my friends is there concept bulk update in insert or update an record or many records in table if no in drupal what is meaning of the bulk update and where this is run and how? thanks alot
0
8365
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
8883
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
0
8788
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
1
8563
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
8646
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
7390
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
0
4372
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
2776
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
2
2013
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.