Solved

Can an insert or update be done without a merge with ADO.NET?

Posted on 2006-07-02
10
182 Views
Last Modified: 2010-04-23
I just wanted to know can an Update or Insert can be done with two different tables without merging them together?  It seems everywhere I look, they want you to merge the tables first, then you are able to update or insert the information from one table to another.  Please let me know.  Thanks!

0
Comment
Question by:VBBRett
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
10 Comments
 
LVL 44

Expert Comment

by:bruintje
ID: 17029205
Hi VBBRett,
----------

what do you mean with merging them?
do you mean 2 tables in different databases? then you can open 2 connections and use the datareader and commandobject to update or insert as needed

for example i have a process reading in a textfile that returns a datatable
then i use that datatable to update or insert records in a SQL db

this is done with no 'merging' as far as i know

----------
bruintje
share what you know, learn what you don't
0
 
LVL 22

Expert Comment

by:Mohammed Nasman
ID: 17029458
Use two SqlCommands objects to update each table
0
 
LVL 41

Expert Comment

by:graye
ID: 17037595
Yes, you may be able to... provided that you perform a bit of magic

If you are certain that there won't be any primary key collisions, then the task is kinda easy...

DataAdapterOne.Fill(DataTableOne)
DataAdapterTwo.Fill(DataTableTwo)

' change the row state to "Added"
for each dr as DataRow in DataTableOne.Rows
       dr.SetAdded        ' new to v2.0
next

' assuming you've got a commandbuilder or other way to create the insert commands
DataAdatperTwo.Update(DataTableOne)

When colisions are anticipated, then the middle part gets a bit complicated

for each dr as DataRow in DataTableOne.Rows
       if DataTableTwo.Contains(dr.colums(0)) then  ' assumes primary key is in col 0
            dr.SetModified       ' new to v2.0
       else
            dr.SetAdded        ' new to v2.0
       end if
next

PS:  Example was typed "by hand"
0
Industry Leaders: We Want Your Opinion!

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

 

Author Comment

by:VBBRett
ID: 17043353
Would you be able to show me how this is done if I give you my code?  here is my code in case you want to modify it.  I'd really apprecaite it.  I didn't show the whole function, just the most important parts to the code.  Thank you once again!

If conn_string.State = ConnectionState.Open Then
                MsgBox("The connection string has connected to the source.")
            Else
                MsgBox("Unable to connect")
            End If


            'The data adapter fills the dataset with the table information from the database
            da.Fill(ds)
            ' da.Fill(ds, "Test_NIP_Valuation_nonproduction")
            da.Fill(dt)

            Dim tester As String
            Dim field1, field2, field3, field4, field5, field6, field7, field8, field9, field10 As String
            Dim field11, field12, field13, field14, field15, field16, field17, field18, field19, field20 As String
            Dim row As DataRow

            Dim retInt As Integer
            Dim count As Integer = 0
            For Each row In ds.Tables(0).Rows

                tester = "insert into jhirniak.NIP_Valuation(LOB, PolicyNO, OccuranceNO, PolOccNo" & _
                "PolComm, LossDay, CAT, RiskState, FirstNotice, ValnMo, AccYr, PdIndem, PdALAE" & _
                "OSIndem, OSALAE, IncdIndem, IncdALAE, IncdLandALAE, Insured, LossDescription" & _
                "Select '" & row.Item("LOB").ToString & ", '" & row.Item("Pol #").ToString & "', '" & _
                row.Item("Occ #").ToString & "', '" & row.Item("Pol Occ #").ToString & "', '" & _
                row.Item("Pol Comm").ToString & "', '" & row.Item("Loss Day").ToString & "', " & _
                row.Item("RiskState").ToString & ", '" & row.Item("First Notice").ToString & "', '" & _
                row.Item("Valn Mo").ToString & "', '" & row.Item("Acc Yr").ToString & "', " & _
                row.Item("PdIndem").ToString & ", '" & row.Item("PdALAE").ToString & ", " & _
                row.Item("OS Indem").ToString & ", " & row.Item("OS ALAE").ToString & ", " & _
                row.Item("IncdIndem").ToString & ", " & row.Item("IncdALAE").ToString & ", " & _
                row.Item("Incd L&ALAE").ToString & ", " & row.Item("Insured").ToString & ", " & _
                row.Item("Loss Description") & "FROM " & Sheetvar & _
                "WHERE NOT EXISTS "







                'row.Item("LOB").ToString & _
                '               row.Item("Pol #").ToString & _
                '              row.Item("Occ #").ToString & _
                '             row.Item("Pol Occ #").ToString & _
                '            row.Item("Pol Comm").ToString & _
                '           row.Item("Loss Day").ToString & _
                '          row.Item("RiskState").ToString & _
                '         row.Item("First Notice").ToString & _
                '        row.Item("Valn Mo").ToString & _
                '       row.Item("Acc Yr").ToString()

                count = count + 1


                If retInt = 1 Then Continue For
                'build update


                MsgBox(tester)
                row.SetAdded()
            Next




        End If
0
 
LVL 41

Accepted Solution

by:
graye earned 500 total points
ID: 17044270
Here is an example, that's closer to what you need.   I made some guesses on a few things, so read the code carefully

        ' The trick is to use two DataAdapters, that share a single DataTable.

        Dim daSource As New SqlClient.SqlDataAdapter
        Dim daDest As New SqlClient.SqlDataAdapter
        Dim con As New SqlClient.SqlConnection
        Dim cb As SqlClient.SqlCommandBuilder
        Dim dr As DataRow
        Dim ds As New DataSet

        ' Fill a DataTable from the non-production table
        daSource.SelectCommand = New SqlClient.SqlCommand("Select * from Test_NIP_Valuation_nonproduction", con)
        daSource.Fill(ds, "Test")

        ' Alter the RowState property
        ' assumes primary key is in col 0
        For Each dr In ds.Tables("Test_NIP_Valuation_nonproduction").Rows
            If ds.Tables("NIP_Valuation").Rows.Contains(dr.Table.Columns(0)) Then
                dr.SetModified()
            Else
                dr.SetAdded()
            End If
        Next

        ' Use a CommandBuilder to create the require Insert/Update commands
        ' (I'm lazy... you *could* code this by hand)
        daDest.SelectCommand = New SqlClient.SqlCommand("Select * from NIP_Valuation", con)
        cb = New SqlClient.SqlCommandBuilder(daDest)

        ' Perform the update of the NIP_Valuation table using the "shared" DataTable
        ' This will either add or update the values for every row in the table
        daDest.Update(ds, "Test")
0
 
LVL 41

Expert Comment

by:graye
ID: 17044307
I had a thought....  this is probably about the same as doing a Merge operation.   In fact, a merge will probably be a lot faster (particularly if you have to leave in the code that checks for duplicates).

So, what was wrong with doing a Merge to begin with?
0
 

Author Comment

by:VBBRett
ID: 17044493
I would get an error with doing a merge.  It did not work.  All I need is an insert.
0
 
LVL 41

Expert Comment

by:graye
ID: 17044700
just curious... what kind of error?

The only failure that I can imagine is a schema-related error or lack of a primary key, etc.   If so, then I'd bet the error will return using my example above
0
 

Author Comment

by:VBBRett
ID: 17044770
Well, I remember looking up the error, and I was told when I did some searching that the table name, the field name, and the datatypes have to be exactly the same...otherwise the command would not execute.
0

Featured Post

Industry Leaders: We Want Your Opinion!

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

This tutorial demonstrates one way to create an application that runs without any Forms but still has a GUI presence via an Icon in the System Tray. The magic lies in Inheriting from the ApplicationContext Class and passing that to Application.Ru…
Article by: jpaulino
XML Literals are a great way to handle XML files and the community doesn’t use it as much as it should.  An XML Literal is like a String (http://msdn.microsoft.com/en-us/library/system.string.aspx) Literal, only instead of starting and ending with w…
This video Micro Tutorial shows how to password-protect PDF files with free software. Many software products can do this, such as Adobe Acrobat (but not Adobe Reader), Nuance PaperPort, and Nuance Power PDF, but they are not free products. This vide…
Monitoring a network: how to monitor network services and why? Michael Kulchisky, MCSE, MCSA, MCP, VTSP, VSP, CCSP outlines the philosophy behind service monitoring and why a handshake validation is critical in network monitoring. Software utilized …

729 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question