Solved

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

Posted on 2006-07-02
10
178 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
Comment Utility
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:mnasman
Comment Utility
Use two SqlCommands objects to update each table
0
 
LVL 41

Expert Comment

by:graye
Comment Utility
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
 

Author Comment

by:VBBRett
Comment Utility
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
How your wiki can always stay up-to-date

Quip doubles as a “living” wiki and a project management tool that evolves with your organization. As you finish projects in Quip, the work remains, easily accessible to all team members, new and old.
- Increase transparency
- Onboard new hires faster
- Access from mobile/offline

 
LVL 41

Accepted Solution

by:
graye earned 500 total points
Comment Utility
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
Comment Utility
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
Comment Utility
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
Comment Utility
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
Comment Utility
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

What Should I Do With This Threat Intelligence?

Are you wondering if you actually need threat intelligence? The answer is yes. We explain the basics for creating useful threat intelligence.

Join & Write a Comment

Well, all of us have seen the multiple EXCEL.EXE's in task manager that won't die even if you call the .close, .dispose methods. Try this method to kill any excels in memory. You can copy the kill function to create a check function and replace the …
Article by: Kraeven
Introduction Remote Share is a simple remote sharing tool, enabling you to see, add and remove remote or local shares. The application is written in VB.NET targeting the .NET framework 2.0. The source code and the compiled programs have been in…
This demo shows you how to set up the containerized NetScaler CPX with NetScaler Management and Analytics System in a non-routable Mesos/Marathon environment for use with Micro-Services applications.
Polish reports in Access so they look terrific. Take yourself to another level. Equations, Back Color, Alternate Back Color. Write easy VBA Code. Tighten space to use less pages. Launch report from a menu, considering criteria only when it is filled…

762 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

Need Help in Real-Time?

Connect with top rated Experts

8 Experts available now in Live!

Get 1:1 Help Now