简体   繁体   English

如何获得外键的入门键值

[英]How to get primery key value to foreign key

I have 3 tables one is User and doctor , patient . 我有3张桌子,一张是Userdoctorpatient User table has common attributes such as ID , Name , Email . User表具有通用属性,例如IDNameEmail 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. 我使用2个SQL Server查询来插入数据。

Foreign key is not automatically get the value from user table ID column. 外键不会自动从用户表ID列中获取值。 Instead of the doctor table foreign key column update as 'null' with other inserted data. 代替doctor表的外键列将与其他插入的数据一起更新为“空”。

I wanna get the user table PK value to doctor table FK . 我想将用户表PK值获取到医生表FK

This is how i insert data into database in asp.net 这就是我将数据插入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 这是SQL Server数据库

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. 触发触发器时,它会向Doctor表中插入一个具有userID的行(其他列为null),然后运行Doctor表插入查询,它将插入除userID之外的所有详细信息。

Im getting 2 rows, i want an one row. 我得到2行,我想要一行。 :( :(

The best method for this in SQL Server is the OUTPUT clause, which is documented here . 在SQL Server中实现此目的的最佳方法是OUTPUT子句,该子句在此处记录

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: 使用SCOPE_IDENTITY()@@IDENTITY或类似方法的优点:

  • There is no concept of "last" modification. 没有“最后”修改的概念。 This simply finds the ids specifically inserted (or updated or deleted) by a given statement. 这只是查找由给定语句专门插入(或更新或删除)的ID。
  • You can pull back more than just the new id field. 您不仅可以拉回新的id字段。 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: SCOPE_IDENTITY函数应该返回最后插入的自动递增的id值:

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 https://msdn.microsoft.com/zh-CN/library/ms190315(v=sql.120).aspx

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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