2013-08-26 82 views
0

我的場景是:我在SQL中有兩個表格,一個是標題,另一個是詳細信息。在標題中刪除記錄時,我想要刪除記錄的詳細信息。在我實際刪除細節之前,我正在做一些檢查。如果不符合條件,則阻止在SQL中刪除語句

我的問題是,當我執行檢查時,我正在基於要刪除的記錄加入Header表,不幸的是,當我這樣做時,標題已被用戶的語句刪除。

如何防止標題被刪除,如果它不符合必要的標準。例如,對於Header表:

Key  | Status 
------------------- 
001  | 00 
002  | 00 
003  | 40 

我的DELETE語句:

DELETE FROM HEADER WHERE KEY = '003' 

在我刪除觸發之前,我刪除我檢查,以確保狀態< 40的細節。如果不是這種情況我拋出一個錯誤,我怎麼能爲Header做同樣的事情?

我的代碼如下:

ALTER TRIGGER [dbo].[trg_PO_DELETE] 

ON PO 

AFTER DELETE 

AS 

DECLARE 
    @Date     DATETIME 
    , @Who     VARCHAR(20) 
    , @ProcessedStatus  CHAR(2) 
    , @ProcessingStatus  CHAR(2) 
    , @ShmtType    INT 
    , @POType    INT 
    , @MsgNo    INT 
    , @Msg     VARCHAR(MAX) 
    , @Continue    INT 

SET @Date     = CURRENT_TIMESTAMP 
SET @Who     = SYSTEM_USER 
SET @ProcessedStatus  = '90' 
SET @ProcessingStatus  = '40' 
SET @ShmtType    = 3 
SET @POType     = 1 
SET @MsgNo     = 0 
SET @Msg     = '' 
SET @Continue    = 0 



IF EXISTS(SELECT 1 FROM PO(NOLOCK) 
       JOIN DELETED ON PO.po_asn_number = DELETED.po_asn_number 
          AND PO.po_customer_id = DELETED.po_customer_id 
          AND PO.po_number = DELETED.po_number 
          AND PO.po_type = DELETED.po_type 
          AND PO.po_status = DELETED.po_status 
      WHERE PO.po_status < @ProcessingStatus) 
    BEGIN 
     /* REMOVE SHIPMENT DETAIL WHEN SHIPMENT HEADER IS DELETED */ 
     DELETE PO_DETAIL 
     FROM PO_DETAIL 
     JOIN DELETED ON PO_DETAIL.pd_asn_number = DELETED.po_asn_number 
        AND PO_DETAIL.pd_customer_id = DELETED.po_customer_id 
        AND PO_DETAIL.pd_po_number = DELETED.po_number 
        AND PO_DETAIL.pd_type = DELETED.po_type 

     /* REMOVE UCC FOR SHIPMENT WHEN SHIPMENT IS DELETED*/ 
     DELETE UCC 
     FROM UCC 
     JOIN DELETED ON UCC.cs_shipment_number = DELETED.po_asn_number 
        AND UCC.cs_po_number = DELETED.po_number 
        AND DELETED.po_type = @ShmtType 

     /* UPDATE PO LEVEL INFORMATION */ 
     UPDATE PO 
       SET PO.po_shipped_qty = PO.po_shipped_qty - DELETED.po_shipped_qty 
       , PO.po_received_qty = PO.po_received_qty - DELETED.po_received_qty 
     FROM PO 
     JOIN DELETED ON PO.po_asn_number = DELETED.po_number 
        AND PO.po_number = DELETED.po_number 
        AND PO.po_customer_id = DELETED.po_customer_id 
        AND DELETED.po_type = @POType 
    END 
ELSE 
    BEGIN 
     SET @Continue = 1 
     SET @MsgNo = 50000 
     SET @Msg = dbo.fnc_GetMessage(@MsgNo) 
    END 
IF @Continue=1 -- Error Occured 
    BEGIN 
     RAISERROR @MsgNo @Msg 
     RETURN 
    END 

我想我的問題是,因爲頭記錄消失之前,我可以做加盟。您可能提供的任何幫助將非常有幫助。

+0

都裹在交易中,做一個ROLLBACK如有錯誤拋出。這就是交易的目的。 – RBarryYoung

+0

謝謝。我將添加交易計數以及INSTEAD OF DELETE – jorame

回答

0

嘗試使用INSTEAD OF DELETE觸發,這樣的事情:

CREATE TRIGGER TEST1 
ON DBO.HEADER 
INSTEAD OF DELETE 
AS 
    BEGIN 
     DELETE H 
     FROM HEADER H 
      INNER JOIN DELETED d 
        ON H.[KEY] = d.[KEY] 
         AND H.STATUS < 40 
    END 

GO