如何将外键id存储在另一个表中

时间:2013-10-13 11:11:08

标签: asp.net

我有四张桌子:

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

1 个答案:

答案 0 :(得分:0)

您只能在T_TADA_tempform表中插入那些ID作为外键,该表包含其父表,如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);