2013-02-14 75 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