简体   繁体   English

如何从主表中获取最大id,并基于此,在主表中插入一条记录,在子表中插入一个或多个条目

[英]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

When I click on add that data will go to child table and above data go to master table. 当我单击添加时 ,数据将进入子表,而上面的数据将进入主表。

Here's a screenshot of the design: 这是设计的屏幕截图:

在此处输入图片说明

save button click event: 保存按钮点击事件:

 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";
    }

You have to write Sql query as below in your procedure and call your procedure from application: 您必须在过程中编写如下的Sql查询,然后从应用程序中调用过程:

 DECLARE @id INT
    INSERT INTO MainPerson VALUES(Name,Age,Male)
    SET @id= SCOPE_IDENTITY()
    INSERT  INTO RelativePerson Values(@id,Name,Relation)

As you have to use the Scope_Identity in order to get the last id inserted to your master table. 因为您必须使用Scope_Identity才能将最后一个ID插入到主表中。

Change Your code to this: 将您的代码更改为此:

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();

And Change Your insertmaster Procedure to: 并将您的insertmaster程序更改为:

Insert into MainTable values(name,age,gender)
Select SCOPE_IDENTITY()

Then you will get the id use that to insert in child table from code. 然后,您将获得用于从代码插入子表中的ID

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM