connection();
String sqlQueryReg = "INSERT INTO StudentReg(Name, City, Address) VALUES(@Name,@City,@Address)";
SqlCommand cmdReg = new SqlCommand(sqlQueryReg, con);
cmdReg.Parameters.AddWithValue("@Name", model.Name);
cmdReg.Parameters.AddWithValue("@City", model.City);
cmdReg.Parameters.AddWithValue("@Address", model.Address);
con.Open();
int iReg = cmdReg.ExecuteNonQuery();
if (iReg >= 1)
{
String sqlQueryInfo = "INSERT INTO StudentInfo(Id, MotherName, FatherName) VALUES(@Id, @MotherName,@FatherName)";
SqlCommand cmdInfo = new SqlCommand(sqlQueryInfo, con);
cmdInfo.Parameters.AddWithValue("@Id", ????????????????);
cmdInfo.Parameters.AddWithValue("@MotherName", model.MotherName);
cmdInfo.Parameters.AddWithValue("@FatherName", model.FatherName);
int iInfo = cmdInfo.ExecuteNonQuery();
}
con.Close();
由于某些原因,我需要分离与1:1关系相关的2个表。[StudentReg]表包含一个自动编号(SQL Server中的身份)。在[StudentRecord]中插入记录后,我需要[Id]字段值,因为我需要将其插入第二张表[StudentInfo]
预期产量
[StudentReg] Table : Note : (Id = Assigned by SQL Server-Identity)
Id | Name | City | Address
1 | John | ABC | DEF
2 | Kent | GHI | PPP
[StudentInfo] Table
Id | Mother Name | Father Name
1 | Maria | Jake
2 | Janice | Frank
最佳答案
使用Scope_Identity
获取当前会话和范围中最后插入的标识值
declare @StudentRegId int
INSERT INTO StudentReg(Name, City, Address) VALUES(@Name,@City,@Address)
select @StudentRegId = scope_identity()
INSERT INTO StudentInfo(Id, MotherName, FatherName) VALUES(@StudentRegId, @MotherName,@FatherName)
关于c# - 具有1:1关系的多重相关表。第一张自动编号表,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/48199498/