从删除级联中的两个表中删除

时间:2018-02-10 10:20:58

标签: sql-server vb.net

如何根据datagridview中的选定行删除数据库中的数据?我已经尝试了我的查询,但它只删除了tblproduct_stocks table上的数据。我想根据产品代码和产品大小删除两个表上的数据。顺便说一句,我使用ON DELETE CASCADE。谢谢你的帮助。

表格

--Table Structure for Products
CREATE TABLE tblproducts (
    product_code varchar(50) NOT NULL PRIMARY KEY,
    product_name varchar(100) NOT NULL,
    product_supplier varchar(50) NOT NULL,
    product_price int NOT NULL
);

--Table Structure for Products Stock In
CREATE TABLE tblproducts_stocks (
    product_stocks_id int NOT NULL IDENTITY(1,1) PRIMARY KEY,
    product_size varchar(30) NOT NULL,
    product_stocks int NOT NULL,
    product_status varchar(50) NOT NULL,
    Date varchar(100) NOT NULL,
    Month varchar(100) NOT NULL,
    Year varchar(100) NOT NULL,
    product_code varchar(50) FOREIGN KEY REFERENCES tblproducts(product_code) ON DELETE CASCADE
);

QUERY

Public Sub deleteProducts()
        productsView.btnDeleteProduct.Text = MessageBox.Show("Are you sure do you want to delete the selected product?", "WARNING: DELETION OF PRODUCT!", MessageBoxButtons.YesNo, MessageBoxIcon.Warning)
        If productsView.btnDeleteProduct.Text = DialogResult.Yes Then
            productsView.btnDeleteProduct.Text = "Delete"
            Try
                dbConnection()
                Dim product_code As String = productsView.productsDGV.SelectedRows(0).Cells("product_code").Value
                Dim product_size As String = productsView.productsDGV.SelectedRows(0).Cells("product_size").Value
                delete_query = "DELETE FROM tblproducts_stocks WHERE product_size = @product_size AND product_code = @product_code;"
                command = New SqlCommand
                With command
                    .Connection = connection
                    .CommandText = delete_query
                    .Parameters.Add("@product_code", SqlDbType.VarChar, 50).Value = product_code
                    .Parameters.Add("@product_size", SqlDbType.VarChar, 30).Value = product_size
                    result = .ExecuteNonQuery()
                    If result = 0 Then
                        MsgBox("Error in deleting product!")
                    Else
                        MsgBox("Successfully deleted the selected product!")
                    End If
                End With
            Catch ex As SqlException
                MsgBox("Error : " + ex.Message)
            Finally
                connection.Close()
                command.Dispose()
                retrieveProducts()
            End Try
        Else
            productsView.btnDeleteProduct.Text = "Delete"
        End If
    End Sub

0 个答案:

没有答案