Solved

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

Posted on 2006-07-02
10
180 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
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
Free Tool: ZipGrep

ZipGrep is a utility that can list and search zip (.war, .ear, .jar, etc) archives for text patterns, without the need to extract the archive's contents.

One of a set of tools we're offering as a way to say thank you for being a part of the community.

 

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

Announcing the Most Valuable Experts of 2016

MVEs are more concerned with the satisfaction of those they help than with the considerable points they can earn. They are the types of people you feel privileged to call colleagues. Join us in honoring this amazing group of Experts.

Question has a verified solution.

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

I think the Typed DataTable and Typed DataSet are very good options when working with data, but I don't like auto-generated code. First, I create an Abstract Class for my DataTables Common Code.  This class Inherits from DataTable. Also, it can …
It was really hard time for me to get the understanding of Delegates in C#. I went through many websites and articles but I found them very clumsy. After going through those sites, I noted down the points in a easy way so here I am sharing that unde…
This video shows how to quickly and easily add an email signature for all users on Exchange 2016. The resulting signature is applied on a server level by Exchange Online. The email signature template has been downloaded from: www.mail-signatures…
Finds all prime numbers in a range requested and places them in a public primes() array. I've demostrated a template size of 30 (2 * 3 * 5) but larger templates can be built such 210  (2 * 3 * 5 * 7) or 2310  (2 * 3 * 5 * 7 * 11). The larger templa…

809 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