2013-02-14 67 views
0

的表已为每个主题(如EnglishLanguage,数学),学生表是关系到每个主题表创造了一个纪录,我很感激,如果有人可以恳请编辑下面的代码使我能够执行删除命令从这些多个表中删除记录。删除从多个表

一个重要的问题是,应该有执行删除命令使得相关记录可以也从随后将在未来引入新主题时创建的任何其他主题表中删除的方法。

Dim cd As String 

If txtName.Text = "" And cboDay.Text = "" And cboMonth.Text = "" And txtYear.Text = "" And lblAge.Text = "" And radioMale.Checked = False Or RadioFemale.Checked = False And txtGName.Text = "" And txtMPhone.Text = "" And txtEmail.Text = "" And txtAddress.Text = "" And txtCity.Text = "" And cboRegion.Text = "" And PictureBox1.ImageLocation = "" Then 
    MessageBox.Show("There is no record selected to delete. Search for the record to delete.", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error) 
Else 
    cd = MessageBox.Show("You are about to delete this record. Are you sure you want to delete?", "Confirm Delete", MessageBoxButtons.YesNo, MessageBoxIcon.Question) 
    If cd = vbYes Then 
     cmd = New SqlCommand("Delete from StudentDetails.Registration where StudentId='" & txtStudentId.Text & "'", cn) 
     cmd.ExecuteNonQuery() 

     cmd = New SqlCommand("Delete from StudentDetails.Students where StudentId='" & txtStudentId.Text & "'", cn) 
     cmd.ExecuteNonQuery() 

     cmd = New SqlCommand("Delete from ProgramDetails.EnglishLanguage where StudentId='" & txtStudentId.Text & "'", cn) 
     cmd.ExecuteNonQuery() 

     MessageBox.Show("Record deleted", "Deleted", MessageBoxButtons.OK, MessageBoxIcon.Information) 
     Showgrid() 
     txtStudentId.Clear() 
     txtName.Clear() 
     cboDay.Text = "" 
     cboMonth.Text = "" 
     lblAge.Text = "" 
     txtNationality.Clear() 
     If radioMale.Checked = True Then 
      Sex = "" 
     End If 
     cboStudentType.Text = "" 
     cboHouse.Text = "" 
     cboRoom.Text = "" 
     txtGName.Clear() 
     txtMPhone.Clear() 
     txtHPhone.Clear() 
     txtEmail.Clear() 
     txtAddress.Clear() 
     txtCity.Clear() 
     cboRegion.Text = "" 
     PictureBox1.Image = PictureBox1.ErrorImage 
     txtStudentId.Focus() 
    End If 
End If 

回答

1

你为什么不试试DELETE CASCADE。它比在代码中手动执行更好。

通过使用级联引用完整性约束,可以定义 行动的SQL服务器,当用户试图删除或更新 一键现有的外键所指向的需要。

ON DELETE CASCADE 指定如果试图删除一行 与在其他 表中现有行的外键,包含这些外键也被删除所有行引用的关键。

至于你所提供的代码,命令应该是这样的:

cmd = New SqlCommand("Delete from StudentDetails.Registration where StudentId=" & Integer.Parse(txtStudentId.Text), cn) 

虽然你应该使用参数化查询,以避免SQL注入:

cmd = New SqlCommand("Delete from StudentDetails.Registration where StudentId = @StudentId" , cn) 
cmd.Parameters.AddWithValue("@StudentId", Integer.Parse(txtStudentId.Text)) 
+0

请您编辑我的关于你的建议的代码。 – Akaglo 2013-02-14 10:20:08

+0

@Akaglo级联方法是通过sql服务器完成的。 – AbZy 2013-02-14 10:21:49

+0

@Akaglo更新了我的答案。 – AbZy 2013-02-14 10:34:55