0

我有四张桌子:

M_Division

Division_ID(primary key) Division

1 abc

2 xyz

M_Designation

Designation_ID(primary key) Designation

1 scientist

2 doctor

M_emp personal


empid(primary key) Divsion_ID(foreign key) Designation_ID(foreign key) emp_name

1 1 1 mike

2 2 2 justin

M_temp

empid(foreign key) Divsion_ID(foreign key) Designation_ID(foreign key) date purpose

1 1 1 12-06-2013 xyz

2 2 2 12-06-2013 abc

我想将外键 ID 插入到 M_temp 表中......如果我给出这样的查询,它会给我外键约束错误......

Insert into M_temp(EmpID,DivisionID,DesigID,date,purpose,reason,created_date) Select(EmpID,DivisionID,DesigID from M_emp_personal where Empid=@empid",conn);

目的,日期是我的 ASP.NET 中的表单字段,它们需要与 DivID DesigID 和 EmpID 一起插入 M_temp ......这就是我面临的问题......我不知道该怎么做有人可以帮帮我吗?

这是 C# 代码

   protected void btnSubmit_Click2(object sender, EventArgs e)
   {
       string RelaseDate = Calendar1.SelectedDate.Date.ToString();

       SqlCommand cmd = new SqlCommand("Insert into T_TADA_tempform(EmpID,DivisionID,DesigID,date,purpose,reason,created_date) values(@EmpID,@DivisionID,@DesigID,@GPFNo,@date,@purpose,@reason), conn);
       cmd.Parameters.AddWithValue("@EmpID", ddlname.SelectedValue);
       cmd.Parameters.AddWithValue("@DivisionID", divisionID);
       cmd.Parameters.AddWithValue("@DesigID", lbldiv.Text);
       cmd.Parameters.AddWithValue("date", RelaseDate);
       cmd.Parameters.AddWithValue("@purpose", ddlpurpose.SelectedValue);

       if (conn.State == ConnectionState.Closed)
       {
           conn.Open();
           int cnt = cmd.ExecuteNonQuery();
           conn.Close();
           if (cnt == 1)
           {
               Response.Redirect("");

           }
           else
               Response.Write("Form has not been submitted,Please Try again!");
       }
   }
4

1 回答 1

0

您只能将这些 id 作为外键插入 T_TADA_tempform 表中,该表包含其父表,如 M_Division 和 M_Designation。

因此,您必须先在 M_Division 和 M_Designation 表中插入记录,然后您可以从此处获取适当的 DivisionID 和 DesigID 插入到主表中。

因此,您可以在 asp.net 表单上显示另外两个下拉列表,它们将从 M_Division 和 M_Designation 表绑定。

您还必须为查询中写入的参数添加所有值,因此您的完整查询将如下所示:

   SqlCommand cmd = new SqlCommand("Insert into T_TADA_tempform(EmpID,DivisionID,DesigID,date,purpose,reason,created_date) values(@EmpID,@DivisionID,@DesigID,@GPFNo,@date,@purpose,@reason,@created_date), conn);
   cmd.Parameters.AddWithValue("@EmpID", ddlname.SelectedValue);
   cmd.Parameters.AddWithValue("@DivisionID", divisionID);
   cmd.Parameters.AddWithValue("@DesigID", lbldiv.Text);
   cmd.Parameters.AddWithValue("date", RelaseDate);
   cmd.Parameters.AddWithValue("@purpose", ddlpurpose.SelectedValue);
   cmd.Parameters.AddWithValue("@reason", "Please put appropriate reason here!");
   cmd.Parameters.AddWithValue("@created_date", DateTime.Now);
于 2013-10-13T17:37:33.963 回答