Microsoft Knowledge Base Email Alertz

KBAlertz.com: (316244) - Explains how to use OpenXML with .NET providers to perform bulk updates and inserts in Visual Basic .NET. Requires SQL Server 2000 to perform this task.

Receive Microsoft Knowledge Base articles by E-Mail?

Every night we scan the Microsoft Knowledge Base. If technologies you're interested in are updated, we'll send you an e-mail. You only get one e-mail a day, and only when new articles are added.

Click here to create a
FREE account
Already have an account?
[Click here to Login]

Search KbAlertz

Advanced Search

Webmasters
Put kbAlertz on your website.
[ Click Here for more! ]





ASP.NET 3.5 Web Hosting with Windows 2008 and SQL 2008: Click Here!
Discount ASP.NET Hosting
ASP.NET 2.0 and 3.5
Windows2008 and SQL2008
US and UK Hosting
KBAlertz referrals get
** SIX MONTHS FREE **


Community Site



We Send hundreds of thousands of emails using ASP.NET Email


ASP.NET 3.5 Web Hosting with Windows 2008 and SQL 2008: Click Here!
Discount ASP.NET Hosting
ASP.NET 2.0 and 3.5
Windows2008 and SQL2008
US and UK Hosting
KBAlertz referrals get
** SIX MONTHS FREE **




Mentioned In








Microsoft Knowledge Base Article

This article contents is Microsoft Copyrighted material.
©2005-©2007 Microsoft Corporation. All rights reserved. Terms of Use | Trademarks




Article ID: 316244 - Last Review: March 12, 2004 - Revision: 1.3

How to perform bulk updates and inserts by using the OpenXML method with .NET providers in Visual Basic .NET

This article was previously published under Q316244

On This Page

INTRODUCTION

This step-by-step article describes how to perform bulk inserts and updates with different Microsoft .NET data providers by using the OpenXML method in Microsoft Visual Basic .NET. The sample project in this article uses the Microsoft SQL Server .NET Managed Provider (SqlClient). However, you can also use the Microsoft OLE DB .NET Managed Provider or the Microsoft ODBC .NET Managed Provider.

Requirements

The following list outlines the recommended hardware, software, network infrastructure, and service packs that you need:
  • Microsoft Windows 2000, Microsoft Windows XP, or Microsoft Windows Server 2003
  • Microsoft Visual Studio .NET
  • Microsoft SQL Server 2000

Create the project

Note This sample project does not contain code that performs error handling.
  1. Use the following code to create a table in your instance of Microsoft SQL Server 2000:
    if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[Employee]') 
    and OBJECTPROPERTY(id, N'IsUserTable') = 1)
    drop table [dbo].[Employee]
    GO
    
    CREATE TABLE [dbo].[Employee] (
    	[EmployeeId] [int] NOT NULL ,
    	[FirstName] [varchar] (100) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[LastName] [varchar] (100) COLLATE SQL_Latin1_General_CP1_CI_AS NULL 
    ) ON [PRIMARY]
    GO
  2. Use the following code to create a stored procedure in your instance of SQL Server 2000:
    CREATE PROC sp_UpdateXML @empdata nText
    AS 
     DECLARE @hDoc int   
     exec sp_xml_preparedocument @hDoc OUTPUT,@empdata   
    
    --This code updates old data.
     UPDATE Employee 
     SET 
       Employee.FirstName = XMLEmployee.FirstName,
       Employee.LastName = XMLEmployee.LastName
     FROM OPENXML(@hDoc, 'NewDataSet/Employee')   
           WITH (EmployeeId Integer, FirstName varchar(100),  LastName varchar(100))  XMLEmployee
    WHERE    Employee.EmployeeId = XMLEmployee.EmployeeId
    
    --This code inserts new data.
    
    Insert Into Employee 
    SELECT   EmployeeId, FirstName, LastName
    	FROM       OPENXML (@hdoc, '/NewDataSet/Employee',1)
    WITH (EmployeeId Integer, FirstName varchar(100),  LastName varchar(100))  XMLEmployee
    Where XMLEmployee.EmployeeId Not IN (Select EmployeeID from Employee)
    
    EXEC sp_xml_removedocument @hDoc
    GO
  3. Start Microsoft Visual Studio .NET, and then create a new Visual Basic .NET Console Application project. By default, the Module1.vb file is created.
  4. Replace the existing code in the Module1.vb file with the following code.

    Note In the following code, modify the connection string for your environment:
    Imports System
    Imports System.Data.SqlClient
    Imports System.Data
    
    Module Module1
    
       Sub Main()
          Try
             BulkInsertUpdate()
             System.Console.WriteLine("Successfully inserted and updated data.")
             System.Console.Read()
          Catch e As System.Data.SqlClient.SqlException
             System.Diagnostics.Debug.WriteLine(e.Message)
             System.Console.WriteLine(e.Message)
          End Try
       End Sub
       Sub BulkInsertUpdate()
          ' Steps:
          ' 1. Create the data set.
          ' 2. Update the data set.
          ' 3. Insert some data.
          ' 4. Save the changed data as XML, and then send the XML to 
          ' SQL Server through the stored procedure.
    
          ' Declaration
          Dim objDS As System.Data.DataSet
          Dim objCon As SqlConnection
          Dim objCom1 As SqlCommand
          Dim objAdpt1 As SqlDataAdapter
          Dim sConn As String
          sConn = "user id=UserName;password=YourPassword;Database=master;Server=ServerName"
          objDS = New DataSet()
          objCon = New SqlConnection(sConn)
          objCon.Open()
          objCom1 = New SqlCommand()
          objCom1.Connection = objCon
          objAdpt1 = New SqlDataAdapter()
    
    
          ' Step 1: Create the data set.
          CreateDataSetFromEmployee(objDS, objCom1, objAdpt1)
    
          ' Step 2: Update the data set.
          Dim tbl As System.Data.DataTable = objDS.Tables("Employee")
          Dim i As Integer = 0
          Dim aRow As DataRow
          For Each aRow In tbl.Rows
             i = i + 1
             aRow("FirstName") = aRow("FirstName").ToString() & i.ToString()
             aRow("LastName") = aRow("LastName").ToString() & i.ToString()
          Next
    
          ' Step 3: Insert some data.
          Dim ii As Integer
          For ii = 1 To 5 Step ii + 1
             Dim NewRow As DataRow = tbl.NewRow()
             Dim j As Integer = ii + 100
             NewRow("EmployeeId") = j
             NewRow("FirstName") = "Fname" + j.ToString()
             NewRow("LastName") = "LName" + j.ToString()
             tbl.Rows.Add(NewRow)
          Next
    
    
          ' 4. Save the changed data as XML, and then send the XML to 
          ' SQL Server through the stored procedure.
          ' In your instance of SQL Server, you have already saved a stored 
          ' procedure that accepts this XML and updates the corresponding table.
    
          SaveThroughXML(objDS, objCon)
       End Sub
    
       Sub SaveThroughXML(ByVal objDS As DataSet, ByVal objCon As SqlConnection)
          'Change the column mapping.
          Dim tbl As DataTable = objDS.Tables("Employee")
          Dim sb As System.Text.StringBuilder = New System.Text.StringBuilder(1000)
          Dim sw As System.IO.StringWriter = New System.IO.StringWriter(sb)
    
          Dim col As DataColumn
          For Each col In tbl.Columns
             col.ColumnMapping = System.Data.MappingType.Attribute
          Next
    
          objDS.WriteXml(sw, System.Data.XmlWriteMode.WriteSchema)
    
          Dim objCom As SqlCommand = New SqlCommand()
          objCom.Connection = objCon
          objCom.CommandType = CommandType.StoredProcedure
          objCom.CommandText = "sp_UpdateXML"
    
          objCom.Parameters.Add(New SqlParameter("@empdata", System.Data.SqlDbType.NText))
          objCom.Parameters(0).Value = sb.ToString()
          objCom.ExecuteNonQuery()
       End Sub
    
       Sub CreateDataSetFromEmployee(ByVal objDS As DataSet, ByVal objCom1 As SqlCommand, ByVal objAdpt1 As SqlDataAdapter)
    
          ' Create related objects.
          objCom1.CommandType = CommandType.Text
          objCom1.CommandText = "Select EmployeeId, FirstName, LastName from Employee"
    
          ' Fill the Orders table.
          objAdpt1.SelectCommand = objCom1
          objAdpt1.TableMappings.Add("Table", "Employee")
          objAdpt1.Fill(objDS)
       End Sub
    End Module
  5. Press F5 to build and run the application. A console window appears with the following message:
    Successfully inserted and updated data.
  6. Press ENTER to close the console window.

REFERENCES

For additional information about using .NET Managed Providers, click the following article number to view the article in the Microsoft Knowledge Base:
313480  (http://kbalertz.com/Feedback.aspx?kbNumber=313480/ ) INFO: Roadmap for .NET data providers

APPLIES TO
  • Microsoft ADO.NET 1.1
  • Microsoft ADO.NET 1.0
  • Microsoft Visual Basic .NET 2003 Standard Edition
  • Microsoft Visual Basic .NET 2002 Standard Edition
  • Microsoft SQL Server 2000 Standard Edition
  • Microsoft SQL Server 2000 64-bit Edition
Keywords: 
kbdatabase kbdataadapter kbxml kbprovider kbsample kbcode kbhowtomaster KB316244
       

Community Feedback System

Very often, it takes hours to solve a problem. Very often, you've looked high and low, and have tried a lot of solutions. When you finally found it, chances are, it was because someone else helped you. Here's your chance to give back. Use our community feedback tool to let others know what worked for you and what didn't.

Please also understand that the community feedback system is not warranted to be correct, it's simply a system that we've built to let people try and help each other. If something in a feedback response doesn't make sense to you, or you're not comfortable making changes that the feedback talks about (like registry edits), please consult a professional.

Thank you for using kbAlertz.com Feedback System.

-- Scott Cate

Be the first to leave feedback, to help others about this knowledge base article.

(Optional) Name

(Optional) Public URL Or Email

Comments
No HTML -- Text Only Please