I have a table (Table1
) with an auto_increment ID
column as the primary key, and it's working well. I also have another table (Table2
) with a foreign key using the ID column from Table1.
Now when I view records from Table2 I see NULL
in the ID
column and I don't get the auto generated numbers. I also tried with Identity(1,1)
and see the same result.
How I can fix this?
As a follow-up, lets say I add a new column to an existing table and want to give it values from 1 to 20. How can I do that?
As Joel mentions, constraint values are not automatically inserted from one table to another. If the foreign key in Table2 is the primary key value from Table1, then you will need to capture @Table1's primary key value before inserting a new row into @Table2.
Here's a common way of doing this. You can run this example in SSMS.
Declare a table variable (@out) to capture the primary key value of Table1 upon a row insert:
Once we have these things we are ready to insert a new row into Table1 and capture its primary key value.
What's of note here is this guy:
This allows us to capture any value inserted into Table1, but in this case, what we care about is
pk_Table1
.If we view the resultset of
@out
:We see the following:
Viewing the resultset of
@Table1
:Returns:
Now that we've captured the primary key of Table1's new row, we can insert a new row into
@Table2
with a value that ties it back to@Table1
.This guy...
Returns the primary key value we captured when inserting a row into
@Table1
.If we look at the resultset of
@Table2
:We see:
And finally, we can join the two tables together based on their relationship:
Which returns:
Obviously, this isn't a deep dive into relating two tables based on a unique value, however, it's easy to understand.
Here is the full example you can run in SSMS: