Как удалить содержимое связанной записи из двух таблиц (используя SQLTransaction)? - PullRequest
1 голос
/ 15 декабря 2011

Я получаю сообщение об ошибке «Формат строки инициализации не соответствует спецификации, начиная с индекса 0», используя следующий код.Команды должны удалить связанную запись из двух таблиц, а именно StudentDetails.Students в качестве основной таблицы и RegistrationDetails.Registration в качестве дочерней таблицы.

Private Sub cmdDelete_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles cmdDelete.Click
    Try
        Dim cd As String

        If txtStudentID.Text = "" And 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 txtPhone.Text = "" And txtEmail.Text = "" And txtAddress.Text = "" And txtTown.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
                Using c As New SqlConnection("connection string")
                    c.Open()
                    Using tx As SqlTransaction = c.BeginTransaction()
                        Try
                            Using cmd As SqlCommand = c.CreateCommand()
                                cmd.CommandText = "delete from RegistrationDetails.Registration where StudentId = @studentId"
                                cmd.Parameters.Add("@studentId", SqlDbType.BigInt).Value = txtStudentID.Text
                                cmd.ExecuteNonQuery()

                                cmd.CommandText = "delete from StudentDetails.Students where StudentId = @studentId"
                                cmd.Parameters.Add("@studentId", SqlDbType.BigInt).Value = txtStudentID.Text
                                cmd.ExecuteNonQuery()

                                tx.Commit()
                            End Using
                        Catch generatedExceptionName As Exception
                            tx.Rollback()
                            ' take care of exception here
                            Throw
                        End Try
                    End Using
                End Using
                MessageBox.Show("Record deleted", "Deleted", MessageBoxButtons.OK, MessageBoxIcon.Information)
                showgrid()
                txtStudentID.Clear()
                txtName.Clear()
                cboDay.Text = ""
                cboMonth.Text = ""
                txtYear.Clear()
                lblAge.Text = ""
                If radioMale.Checked = True Then
                    Gender = ""
                End If
                txtGName.Clear()
                txtPhone.Clear()
                txtEmail.Clear()
                txtAddress.Clear()
                txtTown.Clear()
                cboRegion.Text = ""
                PictureBox1.Image = PictureBox1.ErrorImage
                txtStudentID.Focus()
            End If
        End If
    Catch ex As Exception
        MessageBox.Show(ex.Message)
    End Try
End Sub

1 Ответ

1 голос
/ 15 декабря 2011

Попробуйте, как это может решить вашу проблему.

cmd.CommandText = "delete from RegistrationDetails.Registration where StudentId = @studentId"
Dim sqlParam as SqlParameter = cmd.Parameters.Add("@studentId", SqlDbType.BigInt)
sqlParam.Value = txtStudentID.Text
cmd.ExecuteNonQuery()

cmd.CommandText = "delete from StudentDetails.Students where StudentId = @studentId"
sqlParam.Value = txtStudentID.Text
cmd.ExecuteNonQuery()

На самом деле вы используете один SqlCommand для обоих запросов и каждый раз, когда добавляете один и тот же параметр.

Надеюсь, это поможет вам.

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...