Review the basic and advanced knowledge of SQL through interview questions

Title 1. Data Acquisition-Additions, deletions, revisions and investigations

1. Create a table

// 课程表 --主表
create table subject(
id int not null,
subject varchar(200)
);

//学生表-- 从表
create table student(
id int not null identity(1,1) primary key,//主键自增长 auto_increment/identity(1,1)
name char(20) not null,
sex char(20) not null defult 'F',
subjectid int ,
constraint stu_sub foreign key student(subjectid) references subject(id) //外键:从表引用主表
);

2. Insert value

//直接插入数据
insert into table student(
id,name,sex,subject)
values(
1,'aa','F',001),
2,'bb','M',002);

//检索的数据插入新表
insert into stu_emp(
id,name,sex,subject)
select id,name,sex,subject from student;

//复制一个表到另一张表
select * into b from a;
create table b as select * from a;
//更新表
alter table a add address varchar(100);//新增一列
alter table a drop column address;//删除列
alter table a add primary key(subjectid);//设置主键
drop table a ; //删除后不可找回

3. Update the data

//更新指定数据
update student set sex ='M' , subjectid = 2 where name='aa';
//删除指定数据
delete from student where id = 1;

4. Basic query & connection

4.1 Multi-table connection

left join/right join/inner join /outer join /full ouer join
Left join is based on the left, find out all the data in the left table and the data in the right table that can be matched with the left table
outer join query all the data in the left and right tables and De-duplication, do not reuse full outer join

//联结的两种方式,注意左表一条id可匹配到右表多条时,查询出来的数据量大于左表查询前的数据量。
select * from a left join b on a.id = b.id
select * from a,b where a.id =b.id

4.2 Vertical splicing of union table

select id,name,sex from a union select id,name,sex from b

4.3 Conditional filtering, sorting, and fetching the specified number of rows

select subject ,count(*) from a
where name like 'a%' and sex ='F'//对行进行过滤,不可使用别名
group by  subject //分组,开始可以使用别名
having count(*)>1//可对行进行过滤,也可对聚合后的数据进行过滤,可使用别名
order by subject  desc//排序
limit 1,offset(2);//取指定行数,offset 从多少行开始取数

4.4 The execution order of SQL statements

Start->FROM clause->join->on->WHERE clause->GROUP BY clause->avg, sum->HAVING clause->SELECT clause->distinct->ORDER BY clause->LIMIT Clause -> final result

Two, aggregate function

Except for count, aggregate functions ignore null values ​​and are often used together with group by.

1. Commonly used basic aggregate functions

1.1 count count: count() contains empty values, count(*) does not contain empty values
1.2 avg() average value
1.3 sum()/max() /min()/stdev()/var() addition/maximum/ Min/standard deviation/variance
1.4 count_big() returns the number of items in the specified group. count_big() returns a bigint value, while count() returns an int value.

1.5 Custom functions

Create FUNCTION AggregateString  //自定义函数名
(@Id int)//传入变量
RETURNS varchar(1024) AS //返回变量
BEGIN
	declare @Str varchar(1024) //申明变量
	set @Str = ''
	select @Str = @Str + [Name] from AggregationTable
	where [Id] = @Id
	return @Str
END

select dbo.AggregateString(Id),Id from AggregationTable
group by Id

Three, window function

<窗口函数> over ([partition by <列清单>]
                        order by <排序用列清单>)

Window functions can be roughly divided into the following two types:
1. Aggregate functions that can be used as window functions (sum, avg, count, max, min)
2. Special window functions such as rank, dense_rank, row_number, and leak().
rank() If there are records with the same rank, the following ranks will be skipped.
dense_rank(), the same rank is tied, not skipped, the rank is continuous.

select product_name, product_type, sale_price,
       rank () over (order by sale_price) as ranking,
	   dense_rank () over (order by sale_price) as dense_ranking,
	   row_number () over (order by sale_price) as row_num
from Product;

Insert picture description here

Four, time function

4.1 Get the current date

current_date(--mysql
sysdate -- Oracle
getdate() -- sql server

4.2 dateadd specifies the date plus days

select dateadd(day,2,'2010-10-15')  // --> 2010-10-17
select * from table where time between dateadd(day,-3,getdate()) and getdate() order by c_Id desc

4.3 datediff specifies the time difference during the day

select datediff(day,'2004-09-01','2004-09-18')  -- > 17 

4.4 datepart returns the specified date part

select datename(weekday, '2004-10-15') -- 返回:星期五

4.5 day()、month()、year()

  select 当前日期=convert(varchar(10),getdate(),120) -- > yyyy-mm-dd 120/114 对应不同标准
     ,当前时间=convert(varchar(8),getdate(),114) -- > hh:mi:ss:mmm(24h)
  select datename(dw,'2004-10-15')
  select 本年第多少周=datename(week,'2004-10-15')
     ,今天是周几=datename(weekday,'2004-10-15')

For more details, please refer to: https://blog.csdn.net/weixin_30338461/article/details/95578246

Five, the stored procedure

A set of SQL statements to complete specific functions, divided into system stored procedures and custom stored procedures

5.1 Advantages:

  1. Improve the versatility and portability of the application, and it can be called repeatedly
  2. Can more effectively manage the user's authority to operate the database
  3. Can improve the speed of SQL, a large amount of SQL code or executed multiple times is much faster than a single SQL execution speed.
  4. Reduce network traffic

5.2 The specific sentence is as follows:

-- 建立无参数存储过程
create procedure p1_all
as 
begin
select * from bookinfo
where publish='清华大学出版社'
end  -- 执行后自动存储在存储过程中,可直接调用
execute p1_all; -- 直接调用即可

-- 有参数的存储过程
create proc p3_writer
@editor varchar(8)
as
begin
	select *
	from BookInfo
	where Writer=@editor
end
exec p3_writer '胡伏湘' -- 调用需传入参数

Six, affairs

Maintain data consistency and recoverability

begin tran        -- 开启事务,transcation 的简写
declare @errorNo int    --定义变量,用于记录事务执行过程中的错误次数
set @errorNo=0
begin try
    update Student set C_S_Id='2' where S_StuNo='003'
    set @errorNo=@errorNo+@@ERROR
    select 'S_StuNo=003 已经修改啦'

    update Student set C_S_Id='3' where S_StuNo='002' 
    set @errorNo=@errorNo+@@ERROR            -- @@ERROR 系统全局变量,记录错误次数,出现一次错误 @@ERROR 值+1
    select 'S_StuNo=002 已经修改啦'

    if(@errorNo>0)
    begin
        --抛出自定义的异常,在最后的catch块中统一处理异常
        RAISERROR(233333,16,3)
    end

end try

begin catch
    select ERROR_NUMBER() errorNumber,        --错误代码
           ERROR_SEVERITY() errorSeverity,    --错误严重级别,级别小于10 try catch 捕获不到
           ERROR_STATE() errorState,        --错误状态码
           ERROR_PROCEDURE() errorProcedure,    --出现错误的存储过程或触发器的名称
           ERROR_LINE() errorLine,        --发生错误的行号
           ERROR_MESSAGE() errorMessage        --错误的具体信息

    if(@@trancount>0)    -- @@trancount 系统全局变量,事务开启 @@trancount 值+1,判断事务是否开启
    begin
        rollback tran;        -- 回滚事务
    end
end catch

if(@@trancount>0)
begin
    commit tran;        -- 提交事务
end

Seven, the cursor

The SQL cursor is a temporary database object that can store a copy of the data row stored in the database table, and also a pointer to the data row.

7.1 Function:

1. Traverse the data rows;
2. Save the query results for easy recall later. It is mentioned in the concept that the use of a cursor will save a copy of the data row, so after the cursor is created, the following query can be queried from the copy, which is much faster than directly querying the database.

7.2 Create a cursor:

declare cursor_name  --游标名称,唯一标识
[insensitive] [scroll] cursor 
for
select_statement --查询语句
[for {
   
   read only| update [of column_name [,...n]]}]

7.3 Parameter description:

Insensitive
tells the DBMS to produce a temporary copy of the query results instead of using pointers to the source data in the database table.
When insensitive is specified, any changes to the underlying table will not be reflected in the cursor data. Conversely, changes to the underlying table will be reflected in the cursor data. The insensitive cursor is read-only, so its content cannot be modified, nor can the underlying table data be modified through it.

Scroll
indicates all extraction operations, that is, the fetch option (the specific options are mentioned below). If not specified, only the next extraction can be performed.

Read only
sets the cursor data to be read-only. After specifying read only, changes to the underlying table will not update its cursor data.

update [of column_name[,…n]]
defines the columns that can be changed in the cursor. If only update is specified, it means that all columns can be updated.

7.4 FETCH statement to retrieve data

--创建游标
declare cursor_school scroll cursor 
for
select Num,ChineseName from School order by Num

--打开游标
open cursor_school

--定义变量
declare @num bigint, @schoolname nvarchar(50)

--提取最后一行学校信息
fetch last from cursor_school into @num, @schoolname

print '学校编号:' + cast(@num as varchar) + '学校名称:' + @schoolname

--关闭游标
close cursor_school

In the fetch statement, SQL Server provides six positioning options:

  1. next: Returns the next row of the current row of the result set, and returns the first row for the first fetch.
  2. frior: returns the previous row of the result set, no data is returned for the first fetch.
  3. first: Return the first row of the result set.
  4. last: Return the last row of the result set.
  5. absolute: Move to the nth row of the result set. If n is positive, move from the first row (including the first row) of the result set to the nth row; if n is negative, move from the last row of the result set to the nth row.
  6. relative: Move n lines from the current position of the cursor pointer. If n is a positive number, read the nth row of data from the current position of the cursor; if n is a negative number, read the nth row of data from the current position of the cursor.

7.5 Positioned UPDATE statement and positioned DELETE statement based on cursor

Create a cursor first when using the update or delete statement

//update
update table_name set column_name,... 
where current of cursor_name

//delete
delete from table_name
where current of cursor_name

7.6 Cursor close and release

The data structure occupied by the cursor will not be released after CLOSE (close). Then you need to use the DEALLOCATE statement to release the occupied data structure, which not only deletes the data in the cursor, but also deletes the cursor from the database as an object.

Release cursor statement:

deallocate cusor_name

Eight, view

It is a virtual table, the fields of the view are customized by us, the view is only for query, the data cannot be changed, and the query data comes from the entity table we built.
Advantages:
1. Simplify user operations
2. Can observe the same database from different angles
3. Provide logical independence for reconstructing the database:
Use the view to merge or filter the required data, but it does not affect the data and structure of the original table
3. .Provide security protection for confidential data:
different views can be established for different users to achieve security purposes.

建立视图的语法:
Create view 视图名称[(字段1) (字段2) (字段3)]
AS
Select 查询语句
[with  check  option]
-- 参数:[with check  option]可选项,防止用户对数据插入、删除、更新是操作了视图范围外的基本表的数据。
-- 删除视图的语法:
Drop view 视图名称

Guess you like

Origin blog.csdn.net/XiaoMaEr66/article/details/114207978