当前位置:网站首页>SQL Server knowledge collection 11: Constraints
SQL Server knowledge collection 11: Constraints
2022-07-07 10:42:00 【꧁ small ۣۖ Pigeon ۣۖ Puzi ۣۖ ิ꧂】
1.SQL Server Primary key constraint
PRIMARY KEY brief introduction
A primary key is a column or group of columns that uniquely identifies each row in a table . have access to PRIMARY KEY Constraints create primary keys for tables . If the primary key contains only one column , Then you can put PRIMARY KEY Constraints are defined as column constraints :
CREATE TABLE table_name (
pk_column data_type PRIMARY KEY,
...
);
If the primary key has two or more columns , Must be used PRIMARY KEY Constraints as table constraints :
CREATE TABLE table_name (
pk_column_1 data_type,
pk_column_2 data type,
...
PRIMARY KEY (pk_column_1, pk_column_2)
);
Each table can only have one primary key . All columns participating in the primary key must be defined as NOT NULL
If... Is not specified for these columns NOT NULL constraint ,SQL Server Will automatically set for all primary key columns NOT NULL constraint .
When creating a primary key ,SQL Server It also automatically creates a unique clustered index ( If specified , Non clustered index ).
PRIMARY KEY Examples of constraints
The following example creates a table with a primary key , The primary key contains a column :
CREATE TABLE sales.activities (
activity_id INT PRIMARY KEY IDENTITY,
activity_name VARCHAR (255) NOT NULL,
activity_date DATE NOT NULL
);
Here it is sales.activities In the table , activity_id Columns are primary key columns . activity_id The column contains unique values .
IDENTITY Property is used for activity_id Column to automatically generate a unique integer value .
The following statement creates a named sales.participants New table of , Its primary key consists of two columns :
CREATE TABLE sales.participants(
activity_id int,
customer_id int,
PRIMARY KEY(activity_id, customer_id)
);
In this example , activity_id or customer_id The values in the column can be repeated , But each combination of values in the two columns must be unique Of .
Usually , The table always has the primary key defined at creation . however , Sometimes , The existing table may not have a primary key defined for some reason .
under these circumstances , have access to ALTER TABLE Statement to add a primary key to a table .
Consider the following example . The following statement creates a table without a primary key :
CREATE TABLE sales.events(
event_id INT,
event_name VARCHAR(255),
start_date DATE NOT NULL,
duration DEC(5,2)
);
To put event_id Column as primary key , Please use the following ALTER TABLE sentence :
ALTER TABLE sales.events
ADD PRIMARY KEY(event_id);
2.SQL Server Foreign key constraints
SQL Server Introduction to foreign key constraints
A foreign key is a column or group of columns in a table , It uniquely identifies the row of another table .
vendor_groups and v endor surface , Their structure is as follows :
CREATE TABLE procurement.vendor_groups (
group_id INT IDENTITY PRIMARY KEY,
group_name VARCHAR (100) NOT NULL
);
CREATE TABLE procurement.vendors (
vendor_id INT IDENTITY PRIMARY KEY,
vendor_name VARCHAR(100) NOT NULL,
group_id INT NOT NULL,
);
Each supplier belongs to the supplier group , Each supplier group may have zero or more suppliers . vendor_groups and vendors Table The relationship between them is one to many .
about vendors Every line in the table , Always be able to vendor_groups Find the corresponding row in the table .
however , If you use the current table creation method , Can be in vendors Insert a row into the table instead of vendor_groups The table shows the corresponding The line of .
It can also be deleted vendor_groups The rows in the table , Without updating or deleting vendors Cause... In the table vendors There are orphans in the table That's ok .
To enforce vendor_groups and vendors Links between data in tables , Need to be in vendors Create a foreign key in the table .
To create a foreign key , Please use FOREIGN KEY constraint .
The following statement deletes vendors Table and use FOREIGN KEY The constraint recreates it :
DROP TABLE vendors;
CREATE TABLE procurement.vendors (
vendor_id INT IDENTITY PRIMARY KEY,
vendor_name VARCHAR(100) NOT NULL,
group_id INT NOT NULL,
CONSTRAINT fk_group FOREIGN KEY (group_id)
REFERENCES procurement.vendor_groups(group_id)
);
Now? , vendor_groups The table is called the parent table , This table is the table referenced by the foreign key constraint . vendors A table is called a sub table , The table is outside the application Key constrained table .
In the above sentence , The following sentence is called fk_grou p Of FOREIGN KEY constraint , The constraint will vendors In the table group_id link to vendor_groups In the table group_id :
CONSTRAINT fk_group FOREIGN KEY (group_id) REFERENCES
procurement.vendor_groups(group_id)
SQL
FOREIGN KEY Constraint grammar
establish FOREIGN KEY The general syntax for constraints is as follows :
CONSTRAINT fk_constraint_name
FOREIGN KEY (column_1, column2,...)
REFERENCES parent_table_name(column1,column2,..)
Now let's learn this grammar in detail .
First , stay CONSTRAINT Specify after keyword FOREIGN KEY Constraint name . Constraint names are optional ( You can do it without specifying ), because This can be defined as follows FOREIGN KEY constraint :
FOREIGN KEY (column_1, column2,...)
REFERENCES parent_table_name(column1,column2,..)
under these circumstances ,SQL Server Will automatically be FOREIGN KEY Constraint generation name .
secondly , stay FOREIGN KEY A comma separated list of foreign key columns enclosed in parentheses is specified after the keyword .
Third , Specify the name of the parent table referenced by the foreign key and a list of comma separated columns with links to columns in the child table .
FOREIGN KEY Examples of constraints
First , stay vendor_groups Insert some rows into the table :
INSERT INTO procurement.vendor_groups(group_name)
VALUES(' Third party suppliers '),
(' Premium supplier '),
(' One time supplier ');
secondly , Insert a new supplier with a supplier group into vendors surface :
INSERT INTO procurement.vendors(vendor_name, group_id)
VALUES('ABC Corp', 1);
The above statement works as expected .
Third , Try inserting vendor_groups There is no new supplier of supplier group in the table :
INSERT INTO procurement.vendors(vendor_name, group_id)
VALUES('XYZ Corp',4);
SQL Server Send the following error :
The INSERT statement conflicted with the FOREIGN KEY constraint "fk_group".
The conflict occurred in database "BikeStores", table
"procurement.vendor_groups", column 'group_id'.
In this example , because FOREIGN KEY constraint , vendor_groups In the table group_id The value of the column is 4 My line doesn't exist . therefore SQL Server Reject the insert and issue an error .
Reference operation
Foreign key constraints ensure referential integrity . If there is a corresponding row in the parent table , Only one row can be inserted into the sub table .
Besides , For foreign key constraints Define reference operations when updating or deleting rows in the parent table , As shown below :
FOREIGN KEY (foreign_key_columns)
REFERENCES parent_table(parent_key_columns)
ON UPDATE action
ON DELETE action;
ON UPDATE and ON DELETE Specify the actions that will be performed when updating and deleting rows in the parent table . The following are the allowed operations : NO ACTION , CASCADE , SET NULL and SET DEFAULT .
Delete the row in the parent table
If you delete one or more rows in the parent table , You can set one of the following operations :
ON DELETE NO ACTION :SQL Server Raise an error and roll back the deletion of rows in the parent table .
ON DELETE CASCADE :SQL Server Delete the row in the child table corresponding to the row deleted from the parent table .
ON DELETE SET NULL : If you delete the corresponding row in the parent table , be SQL Server Set the rows in the sub table to NULL . To do this , The foreign key column must be NULL .
ON DELETE SET DEFAULT : If you delete the corresponding row in the parent table ,SQL Server The rows in the sub table are set as their default value . To do this , With a foreign key There are default definitions . Please note that , If no default value is specified , The default value of the nullable column is NULL .
By default , If no action is explicitly specified , be SQL Server Will be applied ON DELETE NO ACTION .
Operation of updating rows in parent table
If you update one or more rows in the parent table , You can set one of the following operations :
- ON UPDATE NO ACTION :SQL Server Raise an error and roll back the update operation of the rows in the parent table .
- ON UPDATE CASCADE : When the row in the parent table is updated ,SQL Server Update the corresponding row in the sub table .
- ON UPDATE SET NULL : When the corresponding row in the parent table is updated ,SQL Server Set the rows in the sub table to NULL. Please note It means , The foreign key must be empty to execute This operation .
- ON UPDATE SET DEFAULT :SQL Server Set default values for rows in child tables , These rows update the corresponding rows in the parent table That's ok .
3.SQL Server Not Null constraint
SQL Server NOT NULL About constraints
SQL Server NOT NULL The constraint only specifies that the column cannot be NULL value .
The following example creates a column with NOT NULL Constrained table : persons , It has the following fields : first_name , last_name and email :
CREATE SCHEMA hr;
GO
CREATE TABLE hr.persons(
person_id INT IDENTITY PRIMARY KEY,
first_name VARCHAR(255) NOT NULL,
last_name VARCHAR(255) NOT NULL,
email VARCHAR(255) NOT NULL,
phone VARCHAR(20)
);
Please note that , In the upper Columns , take NOT NULL Constraints as column constraints .
By default , If not specified NOT NULL constraint , be SQL Server This column will be allowed to accept NULL .
In this example , Only phone Columns are acceptable NULL .
1. take NOT NULL Add constraints to columns
To put NOT NULL Add constraints to existing columns , This can be done in two steps :
First , Update table values , So that there is no... In the column NULL value :
UPDATE table_name
SET column_name = <new_value>
WHERE column_name IS NULL;
secondly , Change the table to change the properties of the column :
ALTER TABLE table_name
ALTER COLUMN column_name data_type NOT NULL;
for example , To put NOT NULL Add constraints to hr.persons Tabular phone Column , Please use the following sentence .
First , If someone doesn't have a phone number , Update the phone number to the company phone number , for example , 0898-88889999 :
UPDATE hr.persons
SET phone = "0898-88889999"
WHER phone IS NULL;
The second step , modify phone The attribute of the column is NOT NULL :
ALTER TABLE hr.persons
ALTER COLUMN phone VARCHAR(20) NOT NULL;
2. Delete NOT NULL constraint
To remove... From the column NOT NULL constraint , Please use ALTER TABLE ALTER COLUMN sentence , As shown below :
ALTER TABLE table_name
ALTER COLUMN column_name NULL;
for example , From you to phone Delete... From the column NOT NULL constraint , Please use the following sentence :
ALTER TABLE hr.pesons
ALTER COLUMN phone NULL;
边栏推荐
- CC2530 zigbee IAR8.10.1环境搭建
- P1031 [NOIP2002 提高组] 均分纸牌
- 移动端通过设置rem使页面内容及字体大小自动调整
- A small problem of bit field and symbol expansion
- SQL Server 知识汇集11 : 约束
- ThreadLocal is not enough
- Those confusing concepts (3): function and class
- CC2530 ZigBee iar8.10.1 environment construction
- 成为优秀的TS体操高手 之 TS 类型体操前置知识储备
- 高级软考(网络规划设计师)该如何备考?
猜你喜欢
ArrayList thread insecurity and Solutions
[actual combat] transformer architecture of the major medical segmentation challenges on the list --nnformer
Find the greatest common divisor and the least common multiple (C language)
1323:【例6.5】活动选择
ArrayList线程不安全和解决方案
Is the soft test intermediate useful??
使用Tansformer分割三维腹部多器官--UNETR实战
Basic introduction of yarn and job submission process
How to successfully pass the senior system architecture designer in the second half of the year?
Unable to open kernel device '\.\vmcidev\vmx': operation completed successfully. Reboot after installing vmware workstation? Module "devicepoweron" failed to start. Failed to start the virtual machine
随机推荐
Using tansformer to segment three-dimensional abdominal multiple organs -- actual battle of unetr
HDU-2196 树形DP学习笔记
P1031 [NOIP2002 提高组] 均分纸牌
Common shortcut keys in IDA
Installation and configuration of slurm resource management and job scheduling system
[email protected] can help us get the log object quickly
BigDecimal数值比较
Experience sharing of software designers preparing for exams
中级网络工程师是什么?主要是考什么,有什么用?
Find the root of equation ax^2+bx+c=0 (C language)
Mendeley--免费的文献管理工具,给论文自动插入参考文献
Find the greatest common divisor and the least common multiple (C language)
对word2vec的一些浅层理解
Elegant controller layer code
How to successfully pass the senior system architecture designer in the second half of the year?
Jump to the mobile terminal page or PC terminal page according to the device information
P1223 排队接水/1319:【例6.1】排队接水
软考中级,软件设计师考试那些内容,考试大纲什么的?
IDA中常见快捷键
China Southern Airlines pa3.1