当前位置:网站首页>SQL Server knowledge gathering 9: modifying data
SQL Server knowledge gathering 9: modifying data
2022-07-07 10:44:00 【꧁ small ۣۖ Pigeon ۣۖ Puzi ۣۖ ิ꧂】
The first 9 section . Modifying data
1. insert sentence
insert Statement to add a new row to the table , Here are insert The most basic form of a statement :
INSERT INTO table_name (column_list)
VALUES (value_list);
First , table_name Specify the name of the table to insert . Usually , The table name is referenced by the schema name ,
for example production.products , among production Is the pattern name , products It's the name of the table .
secondly , column_list Specify a list of one or more columns in which to insert data . The list of columns must be enclosed in parentheses with commas Separator column .
If the column does not appear in the column list , be SQL Server Must be able to provide insert values , Otherwise, you cannot insert rows .
SQL Server Automatically use the following values for the columns available in the table , But it won't appear in INSERT In the column list of the statement :
If the column has [IDENTITY] attribute , Is the next increment value .
If the column has a specified default value , Default .
If the data type of the column is timestamp data type (timestamp), The default is the current timestamp value .
If the column can be NULL value , Then use NULL .
Third , To be in VALUES Clause provides a list of inserted values . Each column in the column list must have a corresponding value in the value list . Besides , The list of values must be enclosed in parentheses .
Create a file called promotions New table of :
CREATE TABLE sales.promotions (
promotion_id INT PRIMARY KEY IDENTITY (1, 1),
promotion_name VARCHAR (255) NOT NULL,
discount NUMERIC (3, 2) DEFAULT 0,
start_date DATE NOT NULL,
expired_date DATE NOT NULL
);
stay sales A schema named promotions New table of . promotions The table has five columns , Include : Promotional identification number
(promotion_id), name (name), discount (discount), Start date (start_date) And expiration date
(expired_date).
promotion_id Is the identification column , So when adding a new row to the table ,SQL Server Its value will be automatically filled .
1. basic INSERT
The following statement inserts a new line into promotions surface :
INSERT INTO sales.promotions (
promotion_name,
discount,
start_date,
expired_date
)
VALUES
(
'2020 Summer sales ',
0.25,
'20200601',
'20200901'
);
In this example , by promotions The four columns in the table specify values . But not for promotion_id Specify a value for the column , because SQL Server Will automatically provide a value for this column .
If INSERT Statement executed successfully , Will return the number of rows inserted .
(1 row affected)
To verify the result of the insert operation
SELECT
*
FROM
sales.promotions;
2. Insert an explicit value into the identity column
Usually , Do not specify a value for the identity column , because SQL Server The value... Will be provided automatically . however , In some cases , You may want to insert values in the identity column , For example, data migration inserts explicit values for identity columns , You must first execute the following statement :
SET IDENTITY_INSERT table_name ON;
To turn off identity insertion , Please use a similar statement :
SET IDENTITY_INSERT table_name OFF;
stay promotion Insert the value identifying the column in the table :
SET IDENTITY_INSERT sales.promotions ON;
INSERT INTO sales.promotions (
promotion_id,
promotion_name,
discount,
start_date,
expired_date
)
VALUES
(
2,
'2020 Spring Promotion ',
0.25,
'20200201',
'20200301'
);
SET IDENTITY_INSERT sales.promotions OFF;
3.Insert Multiple lines
To add multiple rows to a table at once , Please use the following form of INSERT sentence :
INSERT INTO table_name (column_list)
VALUES
(value_list_1),
(value_list_2),
...
(value_list_n);
In this grammar , Do not use a single value list , Instead, insert using multiple comma separated lists of values .
Use this form of INSERT sentence , The number of rows that can be inserted at one time is 1000 That's ok
If you haven't created promotions surface , You can use the following CREATE TABLE sentence :
drop table if exists sales.promotions;
CREATE TABLE sales.promotions (
promotion_id INT PRIMARY KEY IDENTITY (1, 1),
promotion_name VARCHAR (255) NOT NULL,
discount NUMERIC (3, 2) DEFAULT 0,
start_date DATE NOT NULL,
expired_date DATE NOT NULL
);
The following statement adds multiple rows to promotions surface :
-- Delete all records in the table first
DELETE FROM sales.promotions;
-- Start inserting
INSERT INTO sales.promotions (
promotion_name,
discount,
start_date,
expired_date
)
VALUES
(
'2020 Summer sales ',
0.15,
'20200601',
'20200901'
),
(
'2020 Autumn promotion ',
0.20,
'20201001',
'20201101'
),
(
'2020 Winter promotions ',
0.25,
'20201201',
'20210101'
);
2. insert into select sentence
To insert data from another table into another table , Please use the following SQL Server INSERT INTO SELECT sentence :
INSERT [ TOP ( expression ) [ PERCENT ] ]
INTO target_table (column_list)
select_query
In this grammar , The row returned by the query statement is inserted target_table .
This query is a valid way to retrieve data from any other table SELECT sentence .
It must return with column_list The data corresponding to the column specified in
For the convenience of demonstration , Now create a addresses surface :
CREATE TABLE sales.addresses (
address_id INT IDENTITY PRIMARY KEY,
street VARCHAR (255) NOT NULL,
city VARCHAR (50),
state VARCHAR (25),
zip_code VARCHAR (5)
);
1. Insert all rows of a table into another table
The following statement will customers All addresses in the table are inserted into addresses In the table :
INSERT INTO sales.addresses (street, city, state, zip_code)
SELECT
street,
city,
state,
zip_code
FROM
sales.customers
ORDER BY
first_name,
last_name;
To verify the insertion results , Please use the following query :
SELECT
*
FROM
sales.addresses;
3.update sentence
To modify the existing data in the table , Please use the following UPDATE Sentence syntax :
UPDATE table_name
SET c1 = v1, c2 = v2, ... cn = vn
[WHERE condition]
In the above grammar ,
First , Specify the name of the table from which to update data .
secondly , Specify the columns to update c1 , c2 , … , cn And the value v1 , v2 , … vn A list of .
Third , stay WHERE Clause to select the updated row .WHERE Clauses are optional . If you don't specify WHERE Son sentence , Then all rows in the table will be updated .
Create a file called taxes New table of .
drop table if exists sales.taxes;
CREATE TABLE sales.taxes (
tax_id INT PRIMARY KEY IDENTITY (1, 1),
state VARCHAR (50) NOT NULL UNIQUE,
state_tax_rate DEC(3, 2),
avg_local_tax_rate DEC(3, 2),
combined_rate AS state_tax_rate + avg_local_tax_rate,
max_local_tax_rate DEC (3, 2),
updated_at datetime
);
Execute the following statement to insert data taxes surface :
INSERT INTO
sales.taxes(state,state_tax_rate,avg_local_tax_rate,max_local_tax_rate)
VALUES('Alabama',0.04,0.05,0.07);
INSERT INTO
sales.taxes(state,state_tax_rate,avg_local_tax_rate,max_local_tax_rate)
VALUES('Alaska',0,0.01,0.07);
1. Update all lines
The following statement updates taxs A single column of all rows in the table :
UPDATE sales.taxes
SET updated_at = GETDATE();
In this example , Statement will updated_at The value in the column is changed to GETDATE() Function returns the system date and time .
SQL Server Send the following message :
(2 rows affected)
This means that there is 2 The row record has been successfully updated .
The following query is used to verify the update results :
SELECT
*
FROM
sales.taxes;
It is clear from the output that , updated_at The column has been updated with the current date value .
2. Update multi column example
The maximum local tax rate is 1% The state , The following statement will increase the maximum local tax rate 2% , And an increase in the average tax rate 1% .
UPDATE sales.taxes
SET max_local_tax_rate += 0.02,
avg_local_tax_rate += 0.01
WHERE
max_local_tax_rate = 0.01;
4. delete sentence
To delete existing data in the table , Please use the following DELETE Sentence syntax :
DELETE FROM table_name
[WHERE condition]
In the above grammar
First , Specify the name of the table from which you want to delete data .
secondly , stay WHERE Clause to select the row to delete .WHERE Clauses are optional . If you don't specify WHERE Son sentence , Then all rows in the table will be deleted .
With sales.taxes For example
Delete sales.taxes In the table state( state ) by ‘Alabama’ The data of
delete from sales.taxes where state= 'Alabama' ;
----------
(1 Row affected )
Delete all numbers in the table
delete from sales.taxes ;
5.Merge sentence
Suppose there are two tables named : source Table and target surface , And it needs to be based on source The matching values in the table are updated target surface .
Yes Three situations :
source There are some in the table target Rows that do not exist in the table . under these circumstances , Need to put source Insert rows in the table into target In the table .
target There are some in the table source Rows that do not exist in the table . under these circumstances , Need from target Delete row from table .
source Some rows of the table have the same as target The rows in the table have the same key . however , These rows have different values in non key columns . under these circumstances , Need to use from source Table value update target The rows in the table .
The following figure illustrates source Table and target Table and corresponding operations : Insert , Update and delete :
If used alone INSERT , UPDATE and DELETE sentence , You must construct three separate statements , To use the source In the table The matching row data is updated to target surface .
however ,SQL Server Provide MERGE Statement to perform three operations at the same time . Here are MERGE Sentence syntax :
MERGE target_table USING source_table
ON merge_condition
WHEN MATCHED
THEN update_statement
WHEN NOT MATCHED
THEN insert_statement
WHEN NOT MATCHED BY SOURCE
THEN DELETE;
First , stay MERGE Clause source_table Table and target_table surface .
secondly , merge_condition determine source_table How the rows in the table relate to target_table The rows in the table match . It is similar to On join In Clause join Conditions . Usually , Use the key column of the primary key or unique key for matching .
Third , merge_condition There are three states : MATCHED , NOT MATCHED and NOT MATCHED BY SOURCE .
MATCHED : These are the rows that match the merge criteria . In the picture , They are displayed in blue . For matching lines , Need to use source_table The values in the table are updated target_table Rows and columns in the table .
NOT MATCHED : These are source_table The rows in the table , target_table There are no matching rows in the table . In the figure in , They are displayed in orange . under these circumstances , Need to put source_table Add rows from the table to target_table surface . NOT MATCHED BY TARGET Also known as target mismatch .
NO MATCHED BY SOURCE : These are target_table In the table and source_table Any row in the table does not match That's ok . They are shown in green . If you want to target_table Table and source_table Data synchronization in the table , be You need to use this matching condition to start from target_table Delete row from table .
1. SQL Server MERGE Statement example
Suppose there are two tables : sales.category and sales.category_staging , They store sales by product category .
Reference to Next create statement :
CREATE TABLE sales.category (
category_id INT PRIMARY KEY,
category_name VARCHAR(255) NOT NULL,
amount DECIMAL(10 , 2 )
);
INSERT INTO sales.category(category_id, category_name, amount)
VALUES(1,'Children Bicycles',15000),
(2,'Comfort Bicycles',25000),
(3,'Cruisers Bicycles',13000),
(4,'Cyclocross Bicycles',10000);
CREATE TABLE sales.category_staging (
category_id INT PRIMARY KEY,
category_name VARCHAR(255) NOT NULL,
amount DECIMAL(10 , 2 )
);
INSERT INTO sales.category_staging(category_id, category_name, amount)
VALUES(1,'Children Bicycles',15000),
(3,'Cruisers Bicycles',13000),
(4,'Cyclocross Bicycles',20000),
(5,'Electric Bikes',10000),
(6,'Mountain Bikes',10000);
To use sales.category_staging ( Source table ) The value in updates the data to sales.category ( Target table ), Please use the following MERGE sentence :
merge sales.category t using sales.category_staging s
on s.category_id = t.category_id
when matched -- Matched data , Update according to the data of the new table
then update set t.category_name =s.category_name,t.amount = s.amount
when not matched by target -- Unmatched data in the target table , Insert here
then insert (category_id,category_name,amount)-- You cannot write the alias of the table
values (s.category_id,s.category_name,s.amount)
when not matched by source -- Data not found in source table , Delete here
then delete;
The execution process is shown in the figure below
In this example , Use two tables category_id The value in the column is used as the merge condition .
First , sales.category_staging In the table id The value is 1 , 3 , 4 The row of matches the row in the target table , therefore , MERGE Statement update sales.category Category names and in the table amount The value in the column .
secondly , sales.category_staging In the table id The value is 5 and 6 My line is sales.category There is no , therefore MERGE Statement to insert these rows into the target table .
Third , sales.sales_staging There is no sales.category The table has id The value is 2 The line of , therefore , MERGE Statement will delete this line .
In the combined results , sales.category The data in the table and sales.category_staging The data in the table is fully synchronized
边栏推荐
- Mendeley -- a free document management tool that automatically inserts references into papers
- 软考中级有用吗??
- [detailed explanation of Huawei machine test] tall and short people queue up
- Basic introduction of yarn and job submission process
- When do you usually get grades in the soft exam? Online pedaling?
- 深入分析ERC-4907协议的主要内容,思考此协议对NFT市场流动性意义!
- Typescript interface inheritance
- 香橙派OrangePi 4 LTS开发板通过Mini PCIE连接SATA硬盘的操作方法
- Trajectory planning for multi-robot systems: Methods and applications 综述阅读笔记
- Jump to the mobile terminal page or PC terminal page according to the device information
猜你喜欢
Some superficial understanding of word2vec
Summary of router development knowledge
How much review time does it usually take to take the intermediate soft exam?
【实战】霸榜各大医学分割挑战赛的Transformer架构--nnFormer
BUUCTF---Reverse---reverse1
What are the test preparation materials and methods for soft exam information processing technicians?
P1223 排队接水/1319:【例6.1】排队接水
Mendeley -- a free document management tool that automatically inserts references into papers
P1223 queuing for water /1319: [example 6.1] queuing for water
555电路详解
随机推荐
leetcode-560:和为 K 的子数组
【实战】霸榜各大医学分割挑战赛的Transformer架构--nnFormer
What are the test preparation materials and methods for soft exam information processing technicians?
中级网络工程师是什么?主要是考什么,有什么用?
555电路详解
Prototype and prototype chain
ThreadLocal会用可不够
Yarn的基础介绍以及job的提交流程
长列表性能优化方案 memo
【推荐系统 01】Rechub
String formatting
Records on the use of easyflash v3.3
leetcode-304:二维区域和检索 - 矩阵不可变
多线程-异步编排
Différences entre les contraintes monotones et anti - monotones
[recommendation system 02] deepfm, youtubednn, DSSM, MMOE
2022年7月10日“五心公益”活动通知+报名入口(二维码)
Adb 实用命令(网络包、日志、调优相关)
Leetcode-303: region and retrieval - array immutable
深入理解Apache Hudi异步索引机制