当前位置:网站首页>Database learning notes I

Database learning notes I

2022-06-26 07:53:00 sunshine_ 0224

  The term :

DB: database .-- A file dedicated to storing data .
DBMS: Database management system .-- A system for managing data files .
RDBMS: Relational database management system .-- A management system that stores and manages data in tabular form .
DDL: Data definition language .-- Commands for managing storage structures , For example, create a new table , Modify table structure, etc .
DML: Data operation language .-- Commands for managing data in a storage structure , For example, enter a new record 、 Various queries on existing data 、 Delete or modify existing data .
DCL: Data control language .-- User and rights management , For example, new users 、 Authorization for users, etc . 

Sqlserver Some basic commands

One . Database operation
1. Query whether the database exists
if db_id('dbname') is not null;

2. Create database
create database+ Database name ;

3. Modify the name of the database

exec sp_renamedb @dbname= Old database name , @newname= New database name ;

4. Delete the
drop database Database name ;

5. Specified database
use   Database name ;

Modify or delete if “ The database cannot be locked with an exclusive lock , To perform the operation .” error , Query which sessions are currently connected to the database , And then kill them .

Inquire about :select spid from master.dbo.sysprocesses  where dbid=db_id(' Database name ');

Be careful :spid It's lowercase , Get the process id.

kill :kill spid;

Two . Table operations

---- surface ----

1. Check if the list exists
if object_id('textdb','U') is not null ; among U Represents the user table .

2. new table

CREATE TABLE Product(
    [Id] INT PRIMARY KEY,    -- Primary key --
    [Name] NVARCHAR(50) NOT NULL,    -- Non empty constraint --
    [Mark] NVARCHAR(200) NOT NULL UNIQUE,    -- Uniqueness constraint --
    [Time] DATE DEFAULT GETDATE(),    -- Default constraint --
    [Price] INT NOT NULL CHECK([Price]>=10 AND [Price]<=100),    --check constraint , Ask for a price greater than 10, Less than 100--
    [PriceDouble] AS [Price]*2,        --as To automatically calculate fields , You cannot enter a value --
)

3. Modify the name of the table

exec sp_rename ' Original table name ', ' The new name of the table ';

4. Delete table structure

truncate from Table name ; Delete table structure .

delete and drop Delete table data .

---- A temporary table ----

1. Create a temporary table  

 select * into  #TEMP from Product;    from Product Write data to the temporary table .

The temporary table will not disappear until the connection is closed . 

---- Column ----

1. Add fields

alter table Table name add Name Field type not null default 0 ;

2. Modify field name

exec sp_rename '[ Table name ].[ Field name ]',' new field name ' ;

3. Modify field type

alter table Table name alter column Field name Field type ;

Be careful : If the modified field is a key field , With primary key , And the field type is user-defined , With default values , Using the above statement will result in an error .

For example, if there is a default value, there will be an error when one or more objects access this column ( Because the field to be modified is originally numeric , There is a default initial value , Then change it to char The data type will be wrong )

The reason is to add Fname1 Field, the default value is set , Lead to SQL Server to Fname1 Fields are associated with 'DF__HACYU_B__id__5562F3F1' constraint . Just delete 'DF__HACYU_B__id__5562F3F1' constraint , I can modify it Fname1 Data type .

Delete the constraint statement as follows

alter table HACYU_B drop constraint DF__HACYU_B__id__5562F3F1;

4. Delete field

alter  table Table name drop column Field name ;

3、 ... and . Table data operation

1. Query statement
select*from + The name of the table [+where Conditions ];

2. insert data

insert into The name of the table   values ( value 1, value 2,······, value n);  The fields of the table are given values in order .

insert into The name of the table   ( Field 1, Field 2,······) values ( value 1, value 2,······); Assign individual fields to values .

insert into table2 select * from Ttable1;  Batch insert (table2 Is an existing table ).

select  * into table2 From table1;  Batch insert (table2 Table does not exist , It's automatically created ).

3. Update data

update The name of the table  set Field = value [+where Conditions ];

4. Delete table

drop table Table name ;  Clear all data in the table , The table structure is in , You cannot add a condition to the back to delete .

truncate from Table name ; Delete table structure . 

delete from Table name where Conditions ; Delete table data , With conditions .

delete from Table name ; Delete all records in the table , The operation will be recorded in the log , Can recover .

Query command expansion  

1. Column , Table alias

select * from UserInfo as ui 

by UserInfo Alias as ui, Of course as It can be omitted . Once the alias is taken , When calling a table column , Must call with an alias .

2.select Query some columns

select  top 10 * from UserInfo

  • top n Name  : Indicates before query n That's ok
  • top n percent Name  : Indicates the top percent of the view N The data of

3. Sort query

order by  Name   asc|desc

4. Conditions of the query

where Conditions

  • between .. and ... : Between intervals ,, Continuous intervals
  • in(n1,n2) : accord with n1 perhaps n2 Conditions , Discontinuous
  • Logical operators : and | or | not

   Be careful : between Of and Will be looking for sql The nearest in the statement .

5. Fuzzy query

like % _ [] ^

wildcard

  • % Express arbitrarily Zero or more character  
  • _ Signifying Ren Yidan character
  • [a-f] Express a To f Medium Any single character
  • [a,f] Express a or f
  • [^a-c] It means not a To c The characters in

-- Check the class name Zhang

select * from ClassInfo

where sName like ' Zhang %'

-- The second digit of the telephone number is 0-4

where sPhone like '1[^56789]'

  Be careful : In the database CHAR When the type data is less than digits , The number of digits will be automatically supplemented with spaces , If you don't need spaces , have access to RTrim() perhaps LTrim().

6. Link query

Internal connection (INNER JOIN): There are two kinds of , Explicit and implicit . 

External connections fall into three categories : The left outer join (LEFT OUTER JOIN)、 Right connection (RIGHT OUTER JOIN) And all outside connection (FULL OUTER JOIN).

Student  surface

Class surface  

 

1). Internal connection (inner join perhaps join)

The query content strictly corresponds to , Match the rows in the two tables according to the values of the columns common to each table .

Implicit inner join

select  * from Student  s ,  Class  c where s.Class_num = c.Class_no

Display inner connection

select  * from Student  s inner join   Class  c on s.Class_num = c.Class_no

The display and implicit result sets are the same .

2). Left connection (left join perhaps left outer oin)

The result set of the query includes SQL In the sentence All rows of the left table , Matching rows in the right table .

If a row in the left table does not match a row in the right table , A null value is used to represent .

If the data in the left table , There are multiple rows matching in the right table , The left table of query results is displayed in multiple rows . 

select * from Class c left join Student s on Class_num = c.Class_no

select  * from Student  s left join   Class  c on s.Class_num = c.Class_no

  

3). The right connection (right join perhaps right outer join)

The result set of the query includes SQL In the sentence All rows of the right table , Matching rows in the left table

If a row in the right table has no matching row in the left table , The data in the left table is empty .

If the data in the right table , There are multiple rows matching in the left table , The right table of the query result displays multiple rows . 

select * from Class c right join Student s on Class_num = c.Class_no 

 select  * from Student  s right join   Class  c on s.Class_num = c.Class_no

 4). Complete external connection (full join perhaps full outer join)

The result set of the query includes all the rows in the left and right tables

select  * from Student  s full join   Class  c on s.Class_num = c.Class_no

 5). Cross connect

No, WHERE A cross join of a clause produces the Cartesian product of the tables involved in the join .

The number of rows in the first table multiplied by the number of rows in the second table is equal to the size of the Cartesian product result set . 

select  * from Student   cross join   Class   

add WHERE Clause , Return the qualified result set , and inner join The execution result shown is the same .

 select  * from Student  s cross join   Class c  where s.Class_num = c.Class_no

原网站

版权声明
本文为[sunshine_ 0224]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/02/202202170608306218.html