Create a Conditional Constraint without a trigger

62 views Asked by At

I would like to create a database constraint that would disallow all of the child records from being VOIDded.

For any given Transaction there can be many work orders. I want the database to prevent all the work orders for that transaction from being VOIDed. I do not want to use a trigger.

Table Name: Work_Order with PK Work_Order_ID Transaction_ID is a FK to the Transaction table VOID is a bit value

VOID    Work_Order_ID   Transaction_ID
-----   -------------   --------------
1       3838298         3513904
1       3839916         3513904

The objective is to prevent someone from accidentally VOIDing all the work orders for a transaction.


The following does not work... but it seems like it should. BTW, I should have 1 work order per transaction.

Create FUNCTION Count_Non_Voided_Work_Orders
(
    @Transaction_ID [int]
)
RETURNS INT
AS
BEGIN
    
    DECLARE @Count [int]
    Select 
        @Count = ISNULL(count(*),0)
    FROM [Transaction] t
    JOIN [Work_Order] wo on wo.Transaction_ID = t.Transaction_ID AND wo.VOID = 0
    Where t.Transaction_ID = @Transaction_ID

    RETURN @Count
END


Alter Table Work_Order
Add Constraint One_NON_Void_Must_Exist CHECK (dbo.Count_Non_Voided_Work_Orders(Transaction_ID) = 1);
0

There are 0 answers