同时插入到具有相同userID的两个表中

Insert into two tables at same userID at same time

我想一次性添加两个table的数据。

我有两个 table,UserCredentials(userid,username,password,userrole) 和 EmployeeRecord(userid,用户名、名字、姓氏、目的地、国籍)

UserId 是在数据库中生成的两个 tables 中的身份,我正在寻找一种方法可以在插入记录的 EmployeeRecord 中获取 userID,以便我可以在 UserCredentials 中的相同 userId 处插入登录凭据table。两条记录需要同时插入。

这就是我的代码现在的样子:

      create procedure enteremployeerecord ( 

            @firstName varchar(100),
            @lastName varchar(100),
            @desigNation varchar(50),
            @natioNality varchar(50),
            @userName varchar(50),
            @userPassword varchar(50),
            @userRole varchar(50)          
            )
  as
  begin

  insert into EmployeeRecord(username,firstname,lastname,designation,nationality)
  values (@userName,@firstName,@lastName,@desigNation,@natioNality)

  insert into UserCredentials(username,password,userrole)
  values (@userName,@userPassword,@userRole)

这里是 C# 中的 LINQ SQL 代码(不确定两个查询会如何改变)

EmployeeRecordDBClassDataContext con = new EmployeeRecordDBClassDataContext();
con.enteremployeerecord(firstNameTextBox.Text, lastTextBox.Text, desginationTextBox.Text,nationalityTextBox.Text,userNameTextBox.Text, passwordEmployeeTextBox.Text, userRoleTextBox.Text)

我正在使用 VS 2012 和 SQL 服务器 2012

UserId is identity in both tables generated in DB

坏主意。只有一个 table 需要负责标识符。否则,您必须添加大量保护措施以确保记录 总是 同时添加到两个 table 中。

为了便于说明,我们假设 EmployeeRecord 负责生成 UserId。要插入 UserCredentials 只需获取生成的 ID 并将其插入:

@DECLARE @userID int  

insert into EmployeeRecord(username,firstname,lastname,designation,nationality)
values (@userName,@firstName,@lastName,@desigNation,@natioNality)

SELECT @userID = @@SCOPE_IDENTITY()

insert into UserCredentials(userid, username,password,userrole)
values (@userid, @userName,@userPassword,@userRole)

此外,在 table 之间具有逻辑 1:1 关系(这在 SQL 中是不可能实现的,因为您不能同时插入两个 table ) 我会质疑 table 是否应该合并为一个。如果没有理由将它们分开,那么不要将它们分开