Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

copy an identity column into another table

I have 2 tables that are related,both have identity columns for primary keys and i am using a vb form to insert data into them,My problem is that i cannot get the child table to get the primary key of the parent table and use this as its foreign key in my database. the data is inserted fine though no foreign key constraint is made.I am wondering if a trigger will do it and if so how. All my inserting of data is done in vb.

The user wont insert any keys. all these are identity columns that are auto generated. If a trigger is my way out please illustrate with an example.

If there is another way i can do this in VB itself then please advise and an example will be greatly appreciated

Thanks in advance


2 Answers

Two ways came to my mind (will assume SQL Server):

  1. Insert into the first table (parent) and then get the identity key generated with @@IDENTITY then insert the record in the child table with the retrieved value.
  2. Write a stored procedure that inserts both records and uses the @@IDENTITY internally.
like image 190
tekBlues Avatar answered Nov 26 '25 19:11

tekBlues


I would check your database-design: "My problem is that i cannot get the child table to get the primary key of the parent table" On the Child-table you can set a identity-column but not as foreignkey. Please create a new column of datatype int as foreignkey.

create table parent (id int identity(1,1) not null, data varchar(100)...)
create table child (id int identity(1,1) not null, parent_id int not null, data varchar(100)...)

To retrieve the Information stored in your database, use a query like:

select parent.id, parent.data, child.data
from parent, child 
where parent.id = child.parent_id

To insert data into both tables, you have to use two steps:

insert parent(data) values('This is a test for parent-record')
insert child(parent_id, data) values(@@IDENTITY, 'This is testdata for the child record')

Be carefull with the @@IDENTITY Value because if there are triggers fireing at insert behind the parent table you will get probably not the last parent-table identity-value dependig on the work the trigger does.

like image 28
Ice Avatar answered Nov 26 '25 21:11

Ice



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!