删除不同表中的相关记录

时间:2012-08-16 22:32:09

标签: ms-access asp-classic while-loop


我有这三个表[Orders,order_Items,order_comment]

|    -Orders-    |     |  -Order_Items-   |     | -Order_comment- |
|    order_id    |     |  order_RegCode   |     |    order_id     |
| order_RegCode  |

正如您所看到的,这三个表由2个唯一键相关联! order_idorder_RegCode

P.s:order_RegCode不是主键,是一个字符串!

我希望当我删除order_id的任何订单时,删除存储在另外两个表中的所有相关信息。但当我使用Do时,我得到error Operation is not allowed when the object is closed

请指导我。

守则是:

Dim Order_ID
    Order_ID = Int(Request.Form("ID"))

Set Conn = server.createobject("adodb.connection")
Conn.open StrConn
Set Rs = Conn.execute("SELECT * From orders WHERE order_id="& Order_ID &"")
If NOT Rs.EOF then

    RegCode = Rs("order_RegCode")

    '//== Delete Order
    Set Rs = Conn.execute("Delete From orders where order_id = "& orderID &"")

    '//== Delete All Comments Belong to Order
    Set Rs = Conn.execute("Select * From order_comment where order_id = "& Order_ID &"")
    If NOT Rs.EOF then
        Do While NOT Rs.EOF
            Set Rs = Conn.execute("Delete From order_comment where order_id = "& Order_ID &"")
        Rs.MoveNext
        Loop
    End if

    '//== Delete All Items Belong to Order
    Set Rs = Conn.execute("Select * From order_items where order_code = '"& RegCode &"'")
    If NOT Rs.EOF then
        Do While NOT Rs.EOF
            Set Rs = Conn.execute("Delete From order_items where order_code = '"& RegCode &"'")
        Rs.MoveNext
        Loop
    End if

End if

1 个答案:

答案 0 :(得分:1)

您不得将记录集用于操作查询。这些行:

Set Rs = Conn.execute("Delete ...

应该是:

Conn.execute("Delete ...

您不能对所有记录集使用相同的对象。您将需要外循环的记录集和内循环的另一个记录集。不过,我建议:

Dim Order_ID
Order_ID = Int(Request.Form("ID"))

Set Conn = server.CreateObject("adodb.connection")
Conn.Open StrConn
Set rs = Conn.Execute("SELECT * From orders WHERE order_id=" & Order_ID)
If Not rs.EOF Then

    RegCode = rs("order_RegCode")

    '//== Delete Order
    Conn.Execute ("Delete From orders where order_id = " & orderID)
    Conn.Execute ("Delete From order_comment where order_id = " & Order_ID)
    Conn.Execute ("Delete From order_items where order_code = '" & RegCode & "'")

End If