Click here to Skip to main content
15,904,023 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
How do you fill a linking table with the primary key of the main tables using the @@IDENTITY

I am trying to get the autoincremnt id from the PhysicalTest table and save it in my linking table called PatientRecord

CREATE PROCEDURE procAddPhysicalTestCheck
@Height float,
@Weight float,
@BodyMass float,
@BloodPressure nvarchar(10),
@Temperature float,
@RespiratoryRate nvarchar(10),
@HeartRate float
AS
		INSERT INTO PhysicalTest(Height,Weight,BodyMass,BloodPressure,Temprature,RespiratoryRate,HeartRate)
		VALUES(@Height,@Weight,@BodyMass,@BloodPressure,@Temperature,@RespiratoryRate,@HeartRate)
		
		SELECT @@IDENTITY AS 'Identity'
		DECLARE @PhysicalID AS int
		SET @PhysicalID = @@IDENTITY
		
		INSERT INTO PatientRecord(PhysicalTestID)
		VALUES(@PhysicalID)
Posted

1 solution

No need for the SELECT @@IDENTIY row.

DECLARE @PhysicalID AS int
SET @PhysicalID = @@IDENTITY

I would suggest using SCOPE_IDENTITY instead, however.
Scope Identity[^]

I personally don't like this approach, however,
It would make more stable to perform a SELECT FROM the PhysicalTest table on all the input values to guarantee that the row wrote and that you have the ID for that row.

SQL
INSERT INTO PhysicalTest(Height,Weight,BodyMass,BloodPressure,Temprature,RespiratoryRate,HeartRate)
VALUES(@Height,@Weight,@BodyMass,@BloodPressure,@Temperature,@RespiratoryRate,@HeartRate)
		
DECLARE @PhysicalID AS int
SELECT @PhysicalID = [IdFieldName] 
FROM PhysicalTest WHERE Height = @Height AND Weight = @Weight ... AND HeartRate = @HeartRate

IF @PhysicalID IS NOT NULL 
BEGIN
    INSERT INTO PatientRecord(PhysicalTestID) VALUES(@PhysicalID)
END
 
Share this answer
 
v2
Comments
Elrick007 15-Sep-11 4:59am    
hi
the isert into the physicaltest table works but the insert into the PatientRecord does not work. It cant seem to get the primarykey from the PhysicalTest table.

It returns a null value

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