SQL Server – How Can a Primary Key Be Inserted as Foreign Key?

foreign keysql server

Hi I am building an order intake form that will have information submitted belonging to 3 tables. The order table will have the primary key used for the property and customer table.

How can I simultaneously create the primary key via the identity on the order table and insert that into the property and customer table?

SQL please.

Order
OrderKey PK

Property
OrderKey FK

Best Answer

If you insert multiple Order records (pick a new name that's not a keyword, by the way) then you need to use the OUTPUT clause. Otherwise SCOPE_IDENTITY() should work.

Quick example using SCOPE_IDENTITY:

DECLARE @OrderID int

INSERT INTO
  Orders
   (<columns>
VALUES
 (....)

SET @OrderID = SCOPE_IDENTITY()

INSERT INTO
  Properties
   (OrderID, ...)
VALUES
  (@OrderID, ...)