Search code examples
asp.netsqlsql-servertable-relationships

SQL generate a row automatically on table2, when a row is inserted to table1


I have the next table structure:

Users:

columns: user_id, ...


Users_Skins:

columns: user_id, ...

I want that if a users registers (Users is being populated), it will automatically add a row on Users_Skins with the user_id of the Auto Increment, to Users_Skins.

Should I search for the max user_id, and then insert a new row, or there is a better way (probably) ?

EDIT: I'm using SQL Server


Solution

  • If you do not need to insert any additional data to User_Skins the trigger may be useful, something along those lines:

    create trigger UsersInsert
    on Users after insert as
    begin
       insert into Users_Skins(user_id, ...)
       select i.user_id from inserted I         
    end
    

    Instead of trying to find maximum user_id and increment it I would rather use IDENTITY.