Click here to Skip to main content
15,911,360 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Hi all, I'm beginner in programming and am happy to have meet someone like you.

Please how do I delegate auto generated primary key from a database and assign it to a variable and insert it into a table which references it as a foreign key such as from product table and orderDetail table.

Thank you.
Posted
Updated 14-Aug-12 1:29am
v2
Comments
Malli_S 14-Aug-12 7:30am    
I wonder you may have to write Insert triggers. Which database you are using?
ZurdoDev 14-Aug-12 8:55am    
Is this SQL? Is your primary key an Identity field? You can use SCOPE_IDENTITY() to get the last autogenerated value after your insert statement. Store it in a variable and then in your second insert statement you can use it.

1 solution

Let me give you an example(below).
Explanation: Whenever you insert a record to the table, you get the corresponding ID for it for future use. Here we have created autogenerated(Identity) column as PK, ans same PK is referenced when creating Foreign Key constraint for OrderDetails table.


CREATE TABLE [dbo].[OrderInfo](
[OrderID] [int] IDENTITY(1,1) PRIMARY KEY NOT NULL,
[OrderDate] DATETIME NULL,
[CustomerID] int NOT NULL
)

GO


CREATE PROCEDURE [dbo].[sp_Insert_OrderInfo]
(
@CustomerID int,
@OrderID int OUTPUT

)
AS
SET NOCOUNT ON

INSERT INTO [dbo].[OrderInfo]
( [OrderDate]
, [CustomerID]
)
VALUES
( GETDATE()
, @CustomerID
)


SET @OrderID= scope_identity()


GO

CREATE TABLE [dbo].[OrderDetails](
[OrderID] [int] NOT NULL,
[OrderValue] Float NULL,
[ShippingAddress] nvarchar(4000),
[ExpDelDate] DATETIME,
CONSTRAINT fk_OrderID FOREIGN KEY (OrderID)
REFERENCES [dbo].[OrderInfo](OrderID)

)

GO

Thanks,

Kuthuparakkal
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900