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

狂风中的少年 提交于 2019-12-01 06:20:51

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.

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!

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!