Sql Conditional Not Null Constraint

前端 未结 4 1246
臣服心动
臣服心动 2021-02-01 04:20


I am curious to know is it possible to create a conditional not null constraint in sql? In otherwords is it possible to create a constraint such that a column B can be null

4条回答
  •  误落风尘
    2021-02-01 05:21

    Per onedaywhen, this answer is criminally wrong, and an abomination. You can use a CHECK constraint. http://msdn.microsoft.com/en-us/library/ms188258.aspx

    There's not a way to make conditional constraints. You should, however be able to do the job using a trigger. That's what they're for.

    http://msdn.microsoft.com/en-us/library/ms189799.aspx

    CREATE TRIGGER MyTable.ConditionalNullConstraint ON MyTable.ColumnB
    AFTER INSERT
    AS
    IF EXISTS (SELECT *
        FROM inserted
        WHERE A <> 'NEW' AND B IS NULL
        )
    BEGIN
        RAISERROR ('if A is ''NEW'' then B cannot be NULL', 16, 1);
        ROLLBACK TRANSACTION;
    END;
    GO
    

    Note that in the query you'll want to reference inserted which is a special object that behaves like a table, and lets you reference the row(s) that caused the trigger.

    Of course, in this example you'd need to handle AFTER UPDATE also to enforce the constraint, but that's the general idea.

提交回复
热议问题