簡體   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

當我單擊添加時 ,數據將進入子表,而上面的數據將進入主表。

這是設計的屏幕截圖:

在此處輸入圖片說明

保存按鈕點擊事件:

 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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM