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

[ Failed to transfer the external chain picture , The origin station may have anti-theft chain mechanism , It is suggested to save the pictures and upload them directly (img-l3KC3ElO-1653871034983)(D:\ Some notes \SQL Server Note pictures \11.png)]

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

[ Failed to transfer the external chain picture , The origin station may have anti-theft chain mechanism , It is suggested to save the pictures and upload them directly (img-QwRB40mK-1653871034985)(D:\ Some notes \SQL Server Note pictures \12.png)]

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

原网站

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