Still celebrating National IT Professionals Day with 3 months of free Premium Membership. Use Code ITDAY17

x
?
Solved

Copy Data from one datatable to another datatable.

Posted on 2016-10-14
8
Medium Priority
?
67 Views
Last Modified: 2016-10-25
Hi experts!
I have two datasets in SQL and a user form that I am working with is visual studio.  VB language.
Steps I need to accomplish:
1. Get data from SQl table
2. Get data from user form.
3. Combine the data together and update a different SQl table.

Note that Field
+   "RouterID" is a primary key in SQL with identity specification = true.
+ "OrderNumber" is an automatically generated  field on the form.


My code so far:

       ssql = "SELECT OpNo, WorkCenter, "
        ssql = ssql + "OpShortTxt, BaseQty, SetupMachine, SmUnit, SetupLabor, SlUnit, MachineRun, MrUnit, "
        ssql = ssql + "LaborRun, LrUnit, StdVal5, V5Unit, StdVal6, V6Unit "
        ssql = ssql + "from TSAPRouterData Where "
        ssql = ssql + "PartNumber ='" & TxtPartNumber.Text & "' and GroupCounter='" & DgRouters.SelectedRows(0).Cells(1).Value.ToString & "'"

        da = New SqlDataAdapter(ssql, conn)
        cb = New SqlCommandBuilder(da)
        ds = New DataTable
        da.Fill(ds)

        Dim ssql2 As String = "SELECT OpNo, WorkCenter, "
        ssql2 = ssql2 + "OpShortTxt, BaseQty, SetupMachine, SmUnit, SetupLabor, SlUnit, MachineRun, MrUnit, "
        ssql2 = ssql2 + "LaborRun, LrUnit, StdVal5, V5Unit, StdVal6, V6Unit, OrderNumber, RouterID"
        ssql2 = ssql2 + "from TReleasedRouter"

        Dim da2 = New SqlDataAdapter(ssql, conn)
        Dim cb2 = New SqlCommandBuilder(da2)
        Dim ds2 = New DataTable
        da2.Fill(ds2)

        ds2 = ds.Copy()

' My attempt at trying to figure out the primary key thing from Microsoft website.

        Dim keys(2) As DataColumn
        Dim column As DataColumn

        column = New DataColumn()
        column.DataType = System.Type.GetType("System.String")
        column.ColumnName = "OrderNumber"

        ds2.Columns.Add(column)

        column = New DataColumn()
        column.DataType = System.Type.GetType("System.Int16")
        column.ColumnName = "RouterID"
        ds2.Columns.Add(column)

        keys(1) = column
        ds2.PrimaryKey = keys

        Dim i As Integer = 0

' add the information from the form to each datarow and a unique number if necessary but id rather SQl handle the unique number.
        For Each row As DataRow In ds2.Rows
            row.Item("OrderNumber") = TxtCustOrderNo.Text
            row.Item("RouterID") = i
            i = i + 1
        Next

        da2.Update(ds2) <-------ERROR IS HERE

Open in new window


I get this error...
System.InvalidOperationException: Dynamic SQL generation for the UpdateCommand is not supported against a SelectCommand that does not return any key column information.

I am open to the easiest solution possible to get past this error.  If this is crazy convoluted code feel free to suggest alternate working approaches.
0
Comment
Question by:kerrymr
[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
  • 4
  • 2
8 Comments
 
LVL 28

Expert Comment

by:Ark
ID: 41853079
Table adapter can not generate Update, Delete and Insert commandfor tables which doesn't contain primary key. Add PK to second table (TReleasedRouter) using SQL designer.
PS. Or build SQL command manually
0
 
LVL 28

Expert Comment

by:Ark
ID: 41853100
Here is SQL commands:
"IF NOT EXISTS (SELECT * FROM sys.key_constraints WHERE type = 'PK' AND OBJECT_NAME(parent_object_id) = 'TReleasedRouter') ALTER TABLE TReleasedRouter DROP CONSTRAINT pk_TReleasedRouter_RouterID"
"IF COL_LENGTH('TReleasedRouter', 'RouterID') IS NOT NULL ALTER TABLE TReleasedRouter DROP COLUMN RouterID"
"ALTER TABLE TReleasedRouter ADD  RouterID int identity(0,1) not null"
"ALTER TABLE TReleasedRouter ADD CONSTRAINT pk_TReleasedRouter_RouterID primary key(RouterID)"
"IF COL_LENGTH('TReleasedRouter', 'OrderNumber') IS NULL ALTER TABLE TReleasedRouter ADD OrderNumber varchar(50)"
"UPDATE TReleasedRouter SET OrderNumber = '" & TxtCustOrderNo.Text & "'"

Open in new window

1. Drop PK if exists
2. Drop RouterID column if exists
3. Create identity column RouterId
4. Create PK
5. Create OrderNumber column if not exists
6. Fill OrderNumber column
0
 

Expert Comment

by:K R
ID: 41853641
Thanks for the update.
I ended up switching my string to parameter queries.
In case anyone ever has the same problem, google parameter queries.

My sample:
Before you use this code to update the SQL tables, pull the data from your "read" dataset and populate a datatable ds.


        Dim ssql2 As String = "Insert into TReleasedRouter (OpNo, WorkCenter, "
        ssql2 = ssql2 + "OpShortTxt, BaseQty, SetupMachine....

        Using comm As New SqlCommand()
            With comm
                .Connection = conn
                .CommandType = CommandType.Text
                .CommandText = ssql2

                    For Each row As DataRow In ds.Rows
                        .Parameters.AddWithValue("@OpNo", row.Item(0))
                        .Parameters.AddWithValue("@WorkCenter", row.Item(1)).....
                        If conn.State = ConnectionState.Closed Then conn.Open()
                        comm.ExecuteNonQuery()
                        comm.Parameters.Clear()
                    Next
                Catch ex As Exception
                    MsgBox(ex.ToString, vbInformation, "Error")
                    Exit Sub
                Finally
                    If conn.State = ConnectionState.Open Then conn.Close()
                End Try
0
Get free NFR key for Veeam Availability Suite 9.5

Veeam is happy to provide a free NFR license (1 year, 2 sockets) to all certified IT Pros. The license allows for the non-production use of Veeam Availability Suite v9.5 in your home lab, without any feature limitations. It works for both VMware and Hyper-V environments

 
LVL 28

Expert Comment

by:Ark
ID: 41854824
In this case you can do it within 1 command:
ssql = "INSERT INTO TReleasedRouter (OrderNumber, OpNo, WorkCenter, OTHER_COLUMNS)"
ssql += "SELECT '" & TxtCustOrderNo.Text & "', OpNo, WorkCenter, OTHER_COLUMNS "
ssql += "from TSAPRouterData Where "
ssql += "PartNumber ='" & TxtPartNumber.Text & "' and GroupCounter='" 
ssql += "DgRouters.SelectedRows(0).Cells(1).Value.ToString & "'"

Open in new window

0
 
LVL 1

Author Comment

by:kerrymr
ID: 41856851
I used to have the code like this then I read about sql injection attacks.  I thought best practice was a parameterized query.
0
 
LVL 28

Accepted Solution

by:
Ark earned 2000 total points
ID: 41857802
Call this function for all user inputs.
Public Function QuoteString(s As String) As String
    Return "'" & s.Replace("'", "''") & "'"
End Function

Open in new window

You can check user inputs for illegal calls like "Delete FROM..." etc. as well
0
 
LVL 1

Author Closing Comment

by:kerrymr
ID: 41858453
Thanks very much for all your expert knowledge and assistance!
0

Featured Post

Free Tool: SSL Checker

Scans your site and returns information about your SSL implementation and certificate. Helpful for debugging and validating your SSL configuration.

One of a set of tools we are providing to everyone as a way of saying thank you for being a part of the community.

Question has a verified solution.

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

Many of us here at EE write code. Many of us write exceptional code; just as many of us write exception-prone code. As we all should know, exceptions are a mechanism for handling errors which are typically out of our control. From database errors, t…
More often than not, we developers are confronted with a need: a need to make some kind of magic happen via code. Whether it is for a client, for the boss, or for our own personal projects, the need must be satisfied. Most of the time, the Framework…
Have you created a query with information for a calendar? ... and then, abra-cadabra, the calendar is done?! I am going to show you how to make that happen. Visualize your data!  ... really see it To use the code to create a calendar from a q…
Want to learn how to record your desktop screen without having to use an outside camera. Click on this video and learn how to use the cool google extension called "Screencastify"! Step 1: Open a new google tab Step 2: Go to the left hand upper corn…

722 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