当前位置:网站首页>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;
原网站

版权声明
本文为[꧁ small ۣۖ Pigeon ۣۖ Puzi ۣۖ ิ꧂]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/188/202207070831125605.html