table of Contents
What is the difference between rules and constraints?
What are the rules?
It is a single SQL Server object that can be associated with one or several columns in one or several tables. It can use a variety of methods to complete the verification of the data value, you can use the function to return the verification information, and you can also use the keywords BETWEEN, LIKE and IN to complete the check of the input data
In layman's terms: create a rule for a certain column of a table, when the user inserts data, what kind of data can be inserted, what kind of data can not be inserted, play a role in limiting
How to create a rule?
grammar:
CREATE RULE rule_name
AS
codition_expression
Requirements: There is a score table that limits the value of the score entered by the user, which can only be between 0-100
id | cid | score |
1 | 1 | 66 |
2 | 1 | 99 |
3 | 2 | 77 |
The first step is to create rules
--创建规则sc
--设置成绩得取值范围在0和100之间
create rule sc
as
@value between 0 and 100
The second step is to bind rules to specific columns
--绑定规则到score表的score列
sp_bindrule sc,'score.score'
When I insert data into the score column of the score table, the system will automatically report an error
How to delete rules?
Note: If you want to delete a rule, you must “unbind” the rule first, and then delete the rule
Unbind rules
grammar:
--Unbind rules
sp_unbindrule[@obkectname=]<object_name>
[,[@futureonly=]<futureonlu_flag>
Requirements: delete the score rule
--解除规则绑定
sp_unbindrule 'score.score'
--删除规则
drop rule score
Some friends may ask, CHECK constraint also restricts a certain column in the table, then one is not enough, why are there two? What is the difference between them? Let's try it first~~
How to create constraints?
Example: Use the constraint method to specify the range of the score column and limit the input
--创建check约束
--指定字段score输入的分数在0和100之间
create table score_info
(
id int not null,
cid int not null,
score int CHECK( score between 0 and 100)
);
Now insert data into the score field of the score table, and the system will automatically report an error
Related users can also click: https://blog.csdn.net/weixin_43319713/article/details/104320998
What is the difference between rules and constraints?
- The rules are stored separately in the database, and the constraints are linked to the table
- When the table is deleted, the constraint is also deleted, the rule does not
- A field can have multiple constraints, but only one rule