adding CHECK to impose constraints on more than one table

后端 未结 4 1684
我在风中等你
我在风中等你 2021-01-29 02:57

I want to modify the following DDL to add CHECK constraints so that the manager of a store works at the same store and a store supplies all the products if its type is \'local\'

4条回答
  •  面向向阳花
    2021-01-29 03:40

    I see options though the implementation changes depending on the RDBMS:

    • Check constraint calling a function/stored procedure.
    • Trigger, or custom stored procedure.
    • Using insert-select syntax

    Check constraint calling a function

    You will have to create your function, and then utilize it when creating the constraint.

    Examples/Sources:

    • Sub queries in check constraint
    • http://blog.christosoft.de/2012/08/mysql-check-constraint/
    • SQL Server: http://benchmarkitconsulting.com/colin-stasiuk/2011/08/08/check-constraints-that-call-functions/
    • Can I call a user-defined function from a column CHECK constraint?

    Custom Stored Procedure/Function

    In addition to the proposed solution with triggers, another option is to create a stored procedure that is used to insert the data.

    The stored procedure performs the validation, and it the conditions are not met does not insert the data.

    Using Insert with Select

    The below would ensure that a manage entry is not added unless an employee works at the specific store.

    INSERT INTO manager (emploee_number, store_code) AS
    SELECT distinct employee_number,
           store_code
    FROM manages
    WHERE store_code = INPUT_STORE_CODE
      AND employee_number = INPUT_EMPLOYEE_NUMBER
    

提交回复
热议问题