Rules are deprecated, what's instead (TSQL)?

前端 未结 2 1912
慢半拍i
慢半拍i 2021-01-13 19:35

Rules (Transact-SQL)[1] are reusable what permitted to overcome the shortcoming of non-re-usability of check constraints.

And now I read [1] that:

相关标签:
2条回答
  • 2021-01-13 20:18

    If you're concern is you want to write the "code" to constrain once and re-use it on multiple columns, I suggest you do the following:

    Create a function with your constraint rules:

    CREATE FUNCTION schema.PositiveInteger(INT val)
    RETURNS INT AS
    BEGIN
        IF (val > 0) RETURN 1
        ELSE RETURN 0
    END
    

    Add that function as a constraint to the column:

    ALTER TABLE tbl ADD CONSTRAINT chkMyRules CHECK (schema.PositiveInteger(tbl.IntColumn) = 1);
    

    The best part about this is, you can now write re-usable rules that take into account multiple columns.

    CREATE FUNCTION ... (INT val, DATETIME date) RETURNS INT AS ......
    ALTER TABLE tbl ADD CONSTRAINT chkMultipleCols CHECK (func(col1, col2) = 1);
    

    Enjoy!

    0 讨论(0)
  • 2021-01-13 20:20

    Well one reason rules are probably taking the sideline is I believe with rules you can only have one per a column and they only check data going into the database, that is they don't check existing data already in the database. With check constraints you can have multiple constraints on a given column and they enforce on all data(data coming in and data already in the database). Given that rules seem to be a poor man solution to what check constraints are Microsoft probably finally realized it was time to get rid of them, plus they aren't SQL standard.

    If a check constraint doesn't cut it you can also look at using a trigger for more elaborate logic.

    0 讨论(0)
提交回复
热议问题