||SQL Server Tips by Gama and Naughter
Rules are constraints bound to columns from tables or to user
defined data types. They force the data being inserted or updated to
follow certain conditions. Rules contain one line of TSQL, with a
conditional expression, that will enforce the constraint. They
should be simple because their code is executed once for each row
that is inserted or updated.
Rules are a backward compatibility feature and check constraints are
First the CREATE RULE statement will create the new rule, which
needs to be bound to a column with a system stored procedure named
sp_bindrule. Other useful sp's are: sp_help to get info on a rule,
sp_helptext to see the text of a rule and sp_unbindrule to unbind
the rule, before dropping it.
A virtual variable that can take any name will represent the
new/changed data and it should be part of the conditional
Example: add a rule to the phone column from table authors from the
Pubs database. The rule will allow only data in the form 123
456-7890 or UNKNOWN.
This is the code for the rule:
CREATE RULE phone_rule
(@phone='UNKNOWN') OR (LEN(@phone)=12 AND
AND SUBSTRING(@phone,4,1)=' '
AND ISNUMERIC(RIGHT(@phone,4))=1 )
Binding the rule to the column:
EXEC sp_bindrule 'phone_rule', 'authors.phone'
Any attempt to use a different separator for the state or area code,
or using a character other than a number will result in an error
Unbinding the rule (before dropping):
EXEC sp_unbindrule 'authors.phone'
Dropping the rule:
DROP RULE phone_rule
The above book excerpt is from:
Turbocharge Database Performance with C++ External Procedures
Joseph Gama, P. J. Naughter