当前位置:网站首页>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;
边栏推荐
- What are the contents of the intermediate soft test, the software designer test, and the test outline?
- Sword finger offer 38 Arrangement of strings [no description written]
- Five simple and practical daily development functions of chrome are explained in detail. Unlock quickly to improve your efficiency!
- What are the test preparation materials and methods for soft exam information processing technicians?
- Socket communication principle and Practice
- 软考中级有用吗??
- Using U2 net deep network to realize -- certificate photo generation program
- 宁愿把简单的问题说一百遍,也不把复杂的问题做一遍
- 1324:【例6.6】整数区间
- 【OneNote】无法连接到网络,无法同步问题
猜你喜欢
What are the contents of the intermediate soft test, the software designer test, and the test outline?
多线程-异步编排
香橙派OrangePi 4 LTS开发板通过Mini PCIE连接SATA硬盘的操作方法
Some properties of leetcode139 Yang Hui triangle
What are the test preparation materials and methods for soft exam information processing technicians?
软考中级,软件设计师考试那些内容,考试大纲什么的?
Using tansformer to segment three-dimensional abdominal multiple organs -- actual battle of unetr
Openinstall and Hupu have reached a cooperation to mine the data value of sports culture industry
Use load_ decathlon_ Datalist (Monai) fast loading JSON data
Monai version has been updated to 0.9. See what new functions it has
随机推荐
【PyTorch 07】 动手学深度学习——chapter_preliminaries/ndarray 习题动手版
宁愿把简单的问题说一百遍,也不把复杂的问题做一遍
Prototype and prototype chain
使用U2-Net深层网络实现——证件照生成程序
南航 PA3.1
想考中级软考,一般需要多少复习时间?
String formatting
软考中级电子商务师含金量高嘛?
关于easyflash v3.3使用过程的记录
leetcode-303:区域和检索 - 数组不可变
P1031 [noip2002 improvement group] average Solitaire
【OneNote】无法连接到网络,无法同步问题
【机器学习 03】拉格朗日乘子法
[detailed explanation of Huawei machine test] tall and short people queue up
CAS机制
Deeply analyze the main contents of erc-4907 agreement and think about the significance of this agreement to NFT market liquidity!
Leetcode-304: two dimensional area and retrieval - matrix immutable
CC2530 zigbee IAR8.10.1环境搭建
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
移动端通过设置rem使页面内容及字体大小自动调整