 |
|
SQL Server Tips by Gama and Naughter
|
Rules
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
preferable.
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
expression.
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
AS
(@phone='UNKNOWN') OR (LEN(@phone)=12 AND
ISNUMERIC(LEFT(@phone,3))=1
AND SUBSTRING(@phone,4,1)=' '
AND ISNUMERIC(SUBSTRING(@phone,5,3))=1
AND SUBSTRING(@phone,8,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
message.
Unbinding the rule (before dropping):
EXEC sp_unbindrule 'authors.phone'
Dropping the rule:
DROP RULE phone_rule
The above book excerpt is from:
Super SQL
Server Systems
Turbocharge Database Performance with C++ External Procedures
ISBN:
0-9761573-2-2
Joseph Gama, P. J. Naughter
http://www.rampant-books.com/book_2005_2_sql_server_external_procedures.htm
|