[英]how to get max id from master table and based on that insert one record in master table and one or more entry in child table
当我单击添加时 ,数据将进入子表,而上面的数据将进入主表。
这是设计的屏幕截图:
保存按钮点击事件:
protected void btnsave_Click(object sender, EventArgs e)
{
SqlConnection con2 = new SqlConnection(@"Data Source=GLSPL06-PC\GLSPL06;Initial Catalog=example;User ID=sa;Password=sa@123");
con2.Open();
SqlCommand cd = new SqlCommand("insertmaster", con2);
cd.CommandType = CommandType.StoredProcedure;
cd.Parameters.AddWithValue("@name", txtname.Text.Trim());
cd.Parameters.AddWithValue("@age", txtage.Text.Trim());
cd.Parameters.AddWithValue("@gender", Radiogender.SelectedItem.ToString());
cd.ExecuteNonQuery();
con2.Close();
foreach (GridViewRow item in gv.Rows)
{
SqlConnection con = new SqlConnection(@"Data Source=GLSPL06-PC\GLSPL06;Initial Catalog=example;User ID=sa;Password=sa@123");
con.Open();
string statment = string.Format("insert into child_table ( [relative_name], [relation]) values ('{0}','{1}')", item.Cells[0].Text, item.Cells[1].Text);
SqlCommand cmd = new SqlCommand(statment, con);
cmd.CommandType = CommandType.Text;
cmd.ExecuteNonQuery();
con.Close();
}
successmsg.Text = "Data Inserted Successfully";
}
您必须在过程中编写如下的Sql查询,然后从应用程序中调用过程:
DECLARE @id INT
INSERT INTO MainPerson VALUES(Name,Age,Male)
SET @id= SCOPE_IDENTITY()
INSERT INTO RelativePerson Values(@id,Name,Relation)
因为您必须使用Scope_Identity才能将最后一个ID插入到主表中。
将您的代码更改为此:
SqlConnection con2 = new SqlConnection(@"Data Source=GLSPL06-PC\GLSPL06;Initial Catalog=example;User ID=sa;Password=sa@123");
con2.Open();
SqlCommand cd = new SqlCommand("insertmaster", con2);
cd.CommandType = CommandType.StoredProcedure;
cd.Parameters.AddWithValue("@name", txtname.Text.Trim());
cd.Parameters.AddWithValue("@age", txtage.Text.Trim());
cd.Parameters.AddWithValue("@gender", Radiogender.SelectedItem.ToString());
string id = cd.GetScalar();
con2.Close();
并将您的insertmaster程序更改为:
Insert into MainTable values(name,age,gender)
Select SCOPE_IDENTITY()
然后,您将获得用于从代码插入子表中的ID 。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.