SQL T-SQL

1. Variable

 To write sql statements dynamically, there must be no variables.

 Declare variables and assign values :

 

 

 declare @i as int;--定义一个 int 类型的 变量 (as可以省略) print @i;--这注意:没有赋值之前,程序不会报错,而且输出一个 空 set @i=3; print @i;

After sql server 2008, you can assign values ​​to variables while declaring

 

 

declare @a int=3; print @a;

In the process of using variables, we must pay attention to the difference between nvarcahr and nchar.

 

 

declare @s nvarchar(20); set @s='Hello'; set @s=@s+' World!'; print @s;--输出的是 Hello  World!  declare @s2 nchar(20); set @s2='Hello'; set @s2=@s2+' World!'; print @s2;--输出的是 Hello。

Why does nchar output Hello? Because nchar is a fixed length, even if the length does not reach the maximum, but the remaining length is replaced by empty, so it is equivalent to full, so the addition of strings will not work of.

Assign values ​​in the query:

 

 

declare @now datetime; select @now=GETDATE(); print @now; declare @orderNum int; select @orderNum = COUNT(1) from [Sales.Orders];--这条查询语句只是用来 对 变量进行赋值的,不会返回查询结果的. print @orderNum; 

Main function: save the query results in variables for the following use.

In fact, you can also use set assignment to achieve the above effects

 

 

set @orderNum =(select COUNT(1) from [Sales.Orders]) print @orderNum

2. Batch processing

Using "go", all the statements before go are in one batch. Variables of different batches cannot be called mutually.

3. Process control

1) Condition control

 declare @minute int ; set @minute =DATEPART(minute,getdate()); if @minute>20    begin--一条语句可以将  begin end 省略       print '马上睡觉';    end else    print '继续快乐玩耍';

2) Loop control

 

 

  --高斯问题  declare @sum int,@i int;  set @sum=0;  set @i=0;  while @i<100     begin     set @i=@i+1;     set @sum=@sum+@i;     end print @sum;

The use of continue and break in sql server is the same as in c#.

4. Cursor

What is a cursor:

It is not based on the operation of the collection, but the data in the collection is taken out one by one, and the operation is performed one by one.

When to use the cursor:

The default is to use the collection method to query. If you want to use the cursor, you must consider using it with a convincing reason.

Reasons for not using cursors:

1. Using cursors seriously violates the relational model, which is based on set considerations.

2. Operating the records one by one will bring performance overhead. Given a collection, performing a series of cursor code operations on the collection will definitely bring performance overhead, and the performance of this way of using cursors is several times slower than the collection.

3. It takes a lot of code to use the cursor. But if you use a collection, you only query the data you need without describing how to get them. Many codes written by cursors are poorly readable and poorly maintained.

The meaning of existence:

Having said so many drawbacks, is there a meaning for cursors? Of course: When you need to process the queried data one by one, you must use the cursor.

Steps to use the cursor:

1. Declare the cursor in the query

2. Open the cursor

3. Assign the value to the corresponding variable starting from the first value.

4. Loop through the cursor and take the assigned variable to operate.

5. Close the cursor

6, release the cursor

--1、首先在查询基础上声明游标  declare c cursor     for     select shipperid,companyname      from [Sales.Shippers];    --2、打开游标  open c;   --3、从第一个游标开始把 值 赋值到 对应的变量里面 declare @id int,@name nvarchar(20);  --每次取出来一条数据,  添加到指定的 变量。 fetch next from c into @id,@name;  --4、循环遍历 游标,将赋值的变量 拿过来进行相应的操作 while @@FETCH_STATUS=0--等于0代表  游标没有超过最后一行     begin        --相应的操作处理        print @name;                --尝试 读取下一条 数据        fetch next from c into @id,@name;     end  --5、关闭游标 close c;  --6、释放游标 deallocate c;

to sum up:

1. Use cursors, be very cautious, because the performance consumption is very large, absolutely can not be used when uncertain

2. The only advantage of the cursor is that it can perform one-by-one operation on the query data. This is exactly where it adapts.

5. Temporary table

scenes to be used:

When you want to save some data in the table, but don't want to create a data table (because the general company only has the DBA to create the table), or I point to make the current data visible only in the current session, or even as long as the current batch is visible.

Types of temporary tables:

sql server three kinds of temporary tables: local temporary tables, global temporary tables, table variables

The three types of temporary tables are explained separately below:

Local temporary table:

1. The creation process and usage are the same for ordinary tables, and "#" means temporary tables.

2. It is only visible to the session that created him, and is stored in the temporary table of the tempdb data in the system database. After the current session (process) ends, the temporary table will be automatically deleted

3. Temporary tables created by the system in sql server will be suffixed to prevent the creation of the same table name between different processes and to ensure uniqueness.

Ordinary method of creating a temporary table:

create table #partTable (   num int );  insert into #partTable (num) values (1),(2),(3); go;--不再 一个 批 里面 也能使用 ,只要是在同一个 进程里面 select * from #partTable;

Create a temporary table during the query, and insert the query data into the temporary table

 select * into #table from [Sales.Shippers] select * from #table;  

Global temporary table:

1. Add two "#" in front of the table name to represent a global temporary table

2. Note: It is visible to all sessions (processes), but if the current process is closed or the global temporary table is not used for a long time, it will be deleted

 create table ##allTable (   num int ); insert into ##allTable (num) values(1),(2),(3),(4); select * from ##allTable

Table variables:

Note: It will also create a corresponding physical temporary table in the tempdb database, but it is only visible to the "batch" of the current operation, and the temporary table will be deleted after the current batch is executed. (So be sure to note: Table Variables are not stored in memory, he will also create a physical data table)

Performance considerations: When there are only a few rows of data, of course the performance of table variables is good; but if it is a large amount of data, temporary tables should be used

 

 

  declare @tableVariable table  (    num int  )     insert into @tableVariable (num) values (1),(2),(3);  select * from @tableVariable;  go;  --不再同一 批 里面是不能访问到  表 变量 select * from @tableVariable;

The most important point: table variables are the same as variables. When the transaction is rolled back, the value of the variable will not be rolled back. Similarly, table variables will not be rolled back.

 

 

--回滚中 变量的不会回滚的  特殊情况  declare @num int;  set @num =1;  begin transaction;  set @num=12;  print @num;  rollback;  --注意:事务回滚,如果变量在 事务里面 改变,回滚的时候 变量是不会回滚的.  print @num;  --同理:表变量也是如此的 declare @tableVariable2 table (   num int ); insert into @tableVariable2 (num) values(1),(2),(3); begin transaction; delete from @tableVariable2 where num =1; rollback; --表变量是不会 回滚的 select * from @tableVariable2;

6, dynamic sql

What is dynamic sql

First of all, static sql is an ordinary static query statement.

Dynamic SQL: Use exec to execute string SQL statements.

 declare @sql nvarchar(100); set @sql ='select * from [Sales.Shippers]'; exec(@sql)

Disadvantages: Cannot prevent SQL injection vulnerability attacks. (Everyone should know what sql injection vulnerability is. I will not introduce it)

In order to solve the above SQL injection vulnerability attack, a second dynamic SQL appeared: sp_executesql stored procedure:

1. Safe, because it supports the setting of input and output parameters

2. The performance is better than exec: because its parameterization helps reuse cached execution plans. Execution plan: it is the instructions generated when sql server processes sql statements. If you want to reuse the execution plan in the cache, you must ensure that sql The string statements are the same. Therefore, because the parameterized sql statement only needs to replace the parameters, the sql statement can be reused without change.

 

 

  declare @sql nvarchar(100);  set @sql='select * from [Sales.Shippers] where companyname=@name';  declare @name nvarchar(20);  --set @name='顺丰';  set @name='顺丰;select * from [Sales.Shippers]';--即使这样,想要进行sql 注入漏洞攻击,不可能,因为 在sql 语句 把整个 @name里面的 值  作为一个 字符串 来使用的,就是执行 companyname 和 整个字符串的对比    exec sp_executesql     --下面两个是非常重要的    @stmt=@sql,--动态执行的 sql语句   @params=N'@name as nvarchar(20)',--参数的类型   @name=@name;--参数赋值

7. Routine

What is the routine:

A programming phenomenon of code encapsulated in order to calculate results or perform tasks. When it comes to routines, you may not know, but when you mention the following three types, you know all of them.

Types of routines:

User-defined functions, stored procedures, triggers

The most commonly used is the stored procedure, the following first introduces the stored procedure.

Stored procedure:

Create a stored procedure:

 --存储过程:最常用的方法 create procedure MyDemoPro (    --存储过程中 要使用到 的参数    @orderid int ) as --下面是执行的 sql 语句 select * from [Sales.Orders] where orderid=@orderid;

Execute the stored procedure:

 

 

exec MyDemoPro @orderid=10;--可以简写成:exec MyDemoPro 10;

To understand the stored procedure, you must understand its three parameter types:

Incoming parameters, outgoing parameters, return parameters.

Incoming parameters:

It is the ordinary parameter; the one used above is the parameter

Outgoing parameters:

Parameters defined by output: can be transmitted for users to use

 

 

  create procedure OrderCount  (     @count int output  )  as  select @count=COUNT(*) from [Sales.Orders];  go;    --执行 ,一定以声明一个变量 ,赋值给  传出参数 declare @outCount int ; exec OrderCount  @count=@outCount output; print @outCount;

return parameters:

Special parameters: different from c#, it is only used here to indicate the correctness or error of the operation result, only numbers can be returned

 

 

  alter procedure ReturnProc  (     @username nvarchar(100)  )  as    declare @usernameLen int;    set @usernameLen=LEN(@username);        if @usernameLen>=5   return '1';   else   return '0';   declare @result int; --如何为 return 参数 赋值 exec  @result = ReturnProc @username='wanglihong'; print @result;

 If you set a return parameter to'asd', an error will be reported as follows:

Custom function:

1. You can return a value directly  

2. There are two types:

Scalar function (return value is a value)

Table function (the return value is a table) (exist in the function in the programmability)

3. It is rarely used in actual development.

 

 

  create function GetMinute  (     @date datetime  )  --设置返回值:  returns int  as    begin       declare @minute int;      set @minute =datepart(minute,@date);      return @minute;   end  --使用自定义函数 select dbo.GetMinute(GETDATE());

trigger:

Special stored procedures. Main role: retrieval. Note: The trigger must be attached to the event. Only when the event occurs, the trigger is fired and the trigger code is run. (In sql server, there are two events corresponding to triggers: data manipulation events and data definition events, which correspond to the following triggers)

There are two types:

 DML trigger (modification trigger: modification of table data: such as: update, etc.)

 DLL trigger (architecture trigger: modify the database architecture: such as creating a table)

DML trigger:

There are two types:

1. After trigger (operating on the table)

2.instead of trigger (operate on the view)

Note: In the trigger code, only two tables, inserted and deleted, can be accessed. The data update is first deleted and then inserted. The inserted table contains rows of new data after insert and update operations. The deleted table contains rows of old data after delete and update operations.

After triggers are often used, so here is only an introduction to after:

The after trigger is fired after the event associated with it is executed.

Create a log table for the shipper (shipping company) table :

 create table Ship_Log (    id int identity(1,1) primary key,    op_date datetime default getdate(),    op_uaer nvarchar(50),    op      nvarchar(50),    shipname nvarchar(50),    shipphone nvarchar(50) )

 Create a trigger for the table dbo.Sales.Shipper

 

 

 create trigger ship_log_trigger on [Sales.Shippers] after insert as    --当对上面的表进行 增删改的时候执行 触发器的下面的代码    insert into Ship_Log (op_uaer,op,shipname,shipphone)    select user_name()--返回当前操作的用户名    ,'insert',companyname,phone  from inserted;

Insert data into the table dbo.Sales.Shipper to trigger the trigger:

 insert into [Sales.Shippers] (companyname,phone) values('shits','12345678') 

Query log table:

 

 

select * from Ship_Log;

search result:

The log has been inserted.

DLL trigger

Generally not used.

There are two types:

Trigger on the database (for example: create a table)

Trigger to the server (for example: create a database)

8. Identification

Identification: Sometimes we will set the primary key to the identification column (automatically increase the column), and then when querying the identification, we find the value of the newly added identification column.

There are two types:

1. Global scope: @@identity

2. The scope of the current table: SCOPE_IDENTITY(); most commonly used

Note: If you want to insert data into a table that contains triggers, the results of the query will be different (because after inserting data into the table, the trigger will also insert data into the log table, so the global identifier found Is the identifier in the log table, and the identifier in the data table found by SCOPE_IDENTITY())

 insert into [Sales.Shippers] (companyname,phone) values('asd','12345'); select @@identity;--整个数据库中所有的  最新最新增加的 标识列  select SCOPE_IDENTITY();--获得 当前操作的表的最新增加的 标识列的值

If you want to insert data into a table without triggers, the values ​​of the two query identity columns are the same

Guess you like

Origin blog.csdn.net/baidu_39322753/article/details/109377976