Foreign Key Not Populating with Primary Key Values

后端 未结 1 943
难免孤独
难免孤独 2020-11-30 15:59

I have searched for an answer but am not finding it. I have 2 tables. Both have an auto-generated PK. The PK from table 2 is an FK in table 1. Since they are both auto-gener

相关标签:
1条回答
  • 2020-11-30 16:45

    The foreign keys will not auto-populate, as it doesn't know what foreign key to use. You need to either insert the rows into the JobTitle_tbl table, then select the IDs back out (or use @@identity if using sql server)

    select id from JobTitle_tbl where Job_title = ''
    

    Another option would be to update your insert statements to include the primary key, although you'll have to allow identity inserts first.

    SET IDENTITY_INSERT JobTitle_tbl ON
    into the JobTitle_tbl (id, title) values (1, 'Manager')
    SET IDENTITY_INSERT JobTitle_tbl OFF
    

    In either case, you'll need to then update your first insert statements with the ID that you have.

    insert into Employee_tbl (LastName, FirstName, JobID) values ('Smith', 'John', 1)
    
    0 讨论(0)
提交回复
热议问题