2

I have two tables which are linked by foreign key as follows.

userdetails
-----------------------------
uid|username|password|address
-----------------------------

phonedetails
-----------------------------
pid|uid|phone1|phone2
-----------------------------

uid is the foreign key in phonedetails table. I want to insert userdetails in userdetails table and their corresponding phone numbers in phonedetails table.

How can I do it?

Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129
girish
  • 302
  • 1
  • 5
  • 17
  • http://stackoverflow.com/questions/5178697/mysql-insert-into-multiple-tables-database-normalization – Ianis Dec 30 '15 at 15:32

2 Answers2

0

You can make procedure to insert data in both tables.

Procedure will be like this...

  • Insert userdetails data

  • SELECT @uid=SCOPE_IDENTITY() ; -- second step to catch the newly given uid of userdetail table in procedure.

  • Insert phonedetails data using the @uid variable.

More details here SQL - How to INSERT a foreign key as a value for a column

Community
  • 1
  • 1
Anil Panwar
  • 2,592
  • 1
  • 11
  • 24
0

Procedure :

DECLARE @uid INT
INSERT INTO dbo.userdetail
(Col1, Col2)
 VALUES (col1 value, col2 value)
 SELECT @uid =
 SCOPE_IDENTITY();
 INSERT INTO dbo.phonedetails
 (Col1,uid,col3) Values(col1 value,      @uid,col3 value)
Anil Panwar
  • 2,592
  • 1
  • 11
  • 24