Solved

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

Posted on 2006-07-02
10
179 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
Netscaler Common Configuration How To guides

If you use NetScaler you will want to see these guides. The NetScaler How To Guides show administrators how to get NetScaler up and configured by providing instructions for common scenarios and some not so common ones.

 

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

NAS Cloud Backup Strategies

This article explains backup scenarios when using network storage. We review the so-called “3-2-1 strategy” and summarize the methods you can use to send NAS data to the cloud

Question has a verified solution.

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

Suggested Solutions

Title # Comments Views Activity
fso.FolderExists("\\server\HiddenFolder$") 4 66
Help with Syntax 9 37
VS.net 2010 11 36
Create a datatable in vb.net dynamically 1 15
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 …
The ECB site provides FX rates for major currencies since its inception in 1999 in the form of an XML feed. The files have the following format (reducted for brevity) (CODE) There are three files available HERE (http://www.ecb.europa.eu/stats/exch…
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…
A short tutorial showing how to set up an email signature in Outlook on the Web (previously known as OWA). For free email signatures designs, visit https://www.mail-signatures.com/articles/signature-templates/?sts=6651 If you want to manage em…

777 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