简体   繁体   中英

How to get primery key value to foreign key

I have 3 tables one is User and doctor , patient . User table has common attributes such as ID , Name , Email . I have connected both tables using primary key of the user table and foreign key of the doctor table. I use 2 SQL server queries to insert data.

Foreign key is not automatically get the value from user table ID column. Instead of the doctor table foreign key column update as 'null' with other inserted data.

I wanna get the user table PK value to doctor table FK .

This is how i insert data into database in asp.net

sda.InsertCommand = new SqlCommand("Insert into sysUser(userPassword, userType,firstName,lastName,age,dateOfBirth,gender,telephoneNumber,email,userAddress,country) VALUES (@signUpPw, @signUserType,@signUpFname,@signUpLname, @signupAge, @signupDateOfBirth,@signupGender,@signUpTp, @signUpEmail, @signUpAddr, @signUpCountry);", con);

            sda.InsertCommand.Parameters.Add("@signUpPw", SqlDbType.VarChar).Value = newDoctor.getUserPassword();
            sda.InsertCommand.Parameters.Add("@signUserType", SqlDbType.VarChar).Value = "Doctor";/*userType*/
            sda.InsertCommand.Parameters.Add("@signUpFname", SqlDbType.VarChar).Value = newDoctor.firstName;
            sda.InsertCommand.Parameters.Add("@signUpLname", SqlDbType.VarChar).Value = newDoctor.lastName;
            sda.InsertCommand.Parameters.Add("@signupAge", SqlDbType.VarChar).Value = newDoctor.age;

            sda.InsertCommand.Parameters.Add("@signupDateOfBirth", SqlDbType.VarChar).Value = newDoctor.dateOfBirth;
            sda.InsertCommand.Parameters.Add("@signupGender", SqlDbType.VarChar).Value = newDoctor.gender;
            sda.InsertCommand.Parameters.Add("@signUpTp", SqlDbType.VarChar).Value = newDoctor.telephoneNumber;
            sda.InsertCommand.Parameters.Add("@signUpEmail", SqlDbType.VarChar).Value = newDoctor.email;
            sda.InsertCommand.Parameters.Add("@signUpAddr", SqlDbType.VarChar).Value = newDoctor.userAddress;
            sda.InsertCommand.Parameters.Add("@signUpCountry", SqlDbType.VarChar).Value = newDoctor.country;

              con.Open();
              int id = sda.InsertCommand.ExecuteNonQuery();


            sda.InsertCommand = new SqlCommand("Insert into doctor(userID,docTitle, specialityArea, qualifications) VALUES (@signupTitle, @SignupSpecialityArea, @signupQualifications)", con);

            sda.InsertCommand.Parameters.Add("@signupTitle", SqlDbType.VarChar).Value = newDoctor.title;
            sda.InsertCommand.Parameters.Add("@SignupSpecialityArea", SqlDbType.VarChar).Value = newDoctor.specialArea;
            sda.InsertCommand.Parameters.Add("@signupQualifications", SqlDbType.VarChar).Value = newDoctor.qualifications;


            sda.InsertCommand.ExecuteNonQuery();
            con.Close();

and here is the SQL server database

create table sysUser
(userID INT IDENTITY(1,1) NOT NULL PRIMARY KEY, 
userPassword varchar(20) NOT NULL, 
userType varchar(20) NOT NULL, 
firstName varchar(30) NOT NULL, 
lastName varchar(30) NOT NULL, 
age varchar(20) NOT NULL, 
dateOfBirth varchar(20) NOT NULL, 
gender varchar(20) NOT NULL, 
telephoneNumber varchar(20) NOT NULL, 
email varchar(50) NOT NULL, 
userAddress varchar(100) NOT NULL, 
country varchar(50) NOT NULL); 

create table doctor(
docID INT IDENTITY(1,1) NOT NULL PRIMARY KEY,
userID int NOT NULL,
docTitle varchar(20),
specialityArea varchar(200),
qualifications varchar(100)
FOREIGN KEY (userID) REFERENCES sysUser (userID) ON UPDATE NO ACTION ON DELETE CASCADE
);

here is the trigger

CREATE TRIGGER userID_copyTO_doc_FK ON sysUser
FOR INSERT
AS
BEGIN
declare @id int
select @id = userID from inserted  
insert into doctor(userID)
select (@id)
END

when trigger fired it insert a row with userID to the doctor table (other columns are null ) then doctor table insert query runs, it inserts all the details except userID.

Im getting 2 rows, i want an one row. :(

The best method for this in SQL Server is the OUTPUT clause, which is documented here .

The basic idea looks like:

declare @user_ids table (user_id int);

insert into user( . . .)
    output inserted.user_id into @user_ids;
    select . . . ; -- or `values (. . .)`;

You can then use this for subsequent processing:

insert into patient(user_id, . . .)
    select user_id, . . .
    from @user_ids;

The advantages over using SCOPE_IDENTITY() or @@IDENTITY or similar methods:

  • There is no concept of "last" modification. This simply finds the ids specifically inserted (or updated or deleted) by a given statement.
  • You can pull back more than just the new id field. You can pull back any field that was inserted.
  • It is not limited to single row inserts.

SCOPE_IDENTITY function is supposed to return last inserted autoincremented id value:

declare @user_id int

insert into user (...)
values (...)

set @user_id = SCOPE_IDENTITY()

insert into doctor(user_id, ...)
values (@user_id, ...

https://msdn.microsoft.com/en-us/library/ms190315(v=sql.120).aspx

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM