locked
Filling Parent and Child tbales RRS feed

  • Question

  • User-1842273979 posted

    Hello!

    Guys, i need your help with inserting ID from parent to child table. Let me explain. I have a form where users fill name, second name and adress (f.i.)

    There are two tables. Parent table consists of Id (PK field, autoincrement) Name and SeondName fields (string). Another table is Child. Child table consists of ID(PK,AI), Adress field(string) and Parent_ID field(FK). So i need to grab value from Parent,ID field when new record is created in Parent field and put it into Child.Parent_Id field. As you inderstood, i want to fill parent and child tables at the same time. What is the best or easiest way to get ID field value from parent table?

    Thanks in advance!!!

    Tuesday, August 2, 2011 9:25 AM

Answers

  • User-1842273979 posted

    Thankts a lot for help!!!

    I am wondering if it is be confused while few users fill the form simultaneously? it is like both first and second users push the done button of forms. What the way will DB handle with insert statments? will it be  like 1) insert to parent (first user) 2) get id by @@identity 3) insert to child (first user) 4)insert to parent (for second user) 5) get identity 6) insert into child (for send user) . Or it can be like 1) insert to parent (for first user) 2) insert to parent (second user) 3) get identity - in this case @@ identity wil return inly for second user.

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Tuesday, August 2, 2011 10:23 AM

All replies

  • User1644485212 posted

    You can make use of @@identity which will give you your primary key field value.

    insert into parent

    (

    name,

    secondname

    )

    values

    (

    "test first name",

    "test last name"

    )

    DECLARE @pPrimaryIdentity INT

    set @pPrimaryIdentity = @@identity

    insert into child

    (

    address,

    parent_id

    )

    values

    (

    "address",

    @pPrimaryIdentity

    )

    Tuesday, August 2, 2011 10:04 AM
  • User-1842273979 posted

    Thankts a lot for help!!!

    I am wondering if it is be confused while few users fill the form simultaneously? it is like both first and second users push the done button of forms. What the way will DB handle with insert statments? will it be  like 1) insert to parent (first user) 2) get id by @@identity 3) insert to child (first user) 4)insert to parent (for second user) 5) get identity 6) insert into child (for send user) . Or it can be like 1) insert to parent (for first user) 2) insert to parent (second user) 3) get identity - in this case @@ identity wil return inly for second user.

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Tuesday, August 2, 2011 10:23 AM