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();
由于某种原因,我需要分离2个与1:1关系相关的表[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
答案 0 :(得分:0)
使用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)
答案 1 :(得分:0)
如果存在插入触发器,则范围标识将起作用,否则您可以使用ExecuteScalar
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();
另外,请查看.GetLastInsertId()