从多个表中删除记录

时间:2013-02-14 10:11:04

标签: sql-server vb.net winforms tsql ado.net

已经为每个主题创建了一个表(例如EnglishLanguage,Mathematics),学生表与每个主题表相关,如果有人可以编辑下面的代码以使我能够执行删除命令,我将不胜感激从这些多个表中删除记录。

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

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 个答案:

答案 0 :(得分:1)

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

  

通过使用级联参照完整性约束,您可以定义   SQL Server在用户尝试删除时执行的操作   更新现有外键指向的键。

     

ON DELETE CASCADE   指定是否尝试删除行   使用外键在其他行中的现有行中引用的键   表,包含这些外键的所有行也将被删除。

对于您提供的代码,命令应如下所示:

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

虽然您应该使用参数化查询来避免Sql Injection:

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