C# 具有1:1关系的多个相关表。自动编号的第一个表格
出于某种原因,我需要分离与1:1关系相关的两个表[StudentReg]表包含一个自动编号(SQL Server中的标识)。在[StudentRecord]中插入记录后,我需要[Id]字段值,因为我需要将其插入第二个表[StudentInfo] 预期产量C# 具有1:1关系的多个相关表。自动编号的第一个表格,c#,sql-server,asp.net-mvc,C#,Sql Server,Asp.net Mvc,出于某种原因,我需要分离与1:1关系相关的两个表[StudentReg]表包含一个自动编号(SQL Server中的标识)。在[StudentRecord]中插入记录后,我需要[Id]字段值,因为我需要将其插入第二个表[StudentInfo] 预期产量 connection(); String sqlQueryReg = "INSERT INTO StudentReg(Name, City, Address) VALUES(@Name,@City,@Address)"; SqlCommand
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();
使用
Scope\u Identity
获取当前会话和作用域中最后插入的标识值
[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
如果有插入触发器,作用域标识将起作用,如果没有,则可以使用ExecuteScalar
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)
另外,请查看
.GetLastInsertId()
您能提供一些输入和预期输出示例吗?
Int32 savedId;
connection();
String sqlQueryReg = "INSERT INTO StudentReg(Name, City, Address) OUTPUT INSERTED.ID 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);
savedId = (Int32) cmgRed.ExecuteScalar();
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", savedId);
cmdInfo.Parameters.AddWithValue("@MotherName", model.MotherName);
cmdInfo.Parameters.AddWithValue("@FatherName", model.FatherName);
int iInfo = cmdInfo.ExecuteNonQuery();
}
con.Close();