Click here to Skip to main content
15,912,837 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
using sql SERVER 2014
I have table address contains addID PK identity(1,1), city varchar()
table client contains CLNAME varchar(), clID PK, addID foreign key from previous table.
i have a form that allows me to add new address with a new client
the address is added correctly and giving it a new addID automatically (IDENTITY (1,1)) but an error occurs since the addID in client is not inserted automatically
i need to get the max value of addID from table address and add it to my data-row in a data set containing table "client" in order to update the data base

What I have tried:

VB
sqlconn = conxn()
        Dim dset As New DataSet("client")
        Dim dadpt As New SqlDataAdapter("select * From client", sqlconn)
        dadpt.Fill(dset, "client")
        Dim dsADRS As New DataSet("adrs")
        Dim daADRS As New SqlDataAdapter("SELECT MAX(addID) FROM addres ", sqlconn)
        daADRS.Fill(dsADRS, "adrs")
        sen  = 
 

        sqlconn.Close()
 
        Dim cmdBuilder As SqlCommandBuilder = New SqlCommandBuilder(dadpt)
        Dim dr As DataRow
        dr = dset.Tables("client").NewRow()
 
        dr("name") = name
        dr("fname") = fname
      
        dr("addID") = Convert.ToDecimal(sqls)
        dset.Tables("lawyer").Rows.Add(dr)
        dadpt.Update(dset, "lawyer")
Posted
Updated 21-Aug-17 9:46am
v2
Comments
PIEBALDconsult 20-Aug-17 22:41pm    
I recommend against using IDENTITY, particularly in cases such as this.
One option is to use a SEQUENCE instead.
Either way, you need to INSERT the parent row prior to the child row.

And generally, please learn better database techniques.

1 solution

You do not want to SELECT MAX. Instead, right after doing the insert into the address table do
SQL
SELECT @newAddID = SCOPE_IDENTITY()  -- this gets the most recently inserted Identity number

...


INSERT INTO client (field1, ship_to_add_id, ...)
VALUES (@field1, @newAddID...)
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900