Creation and Use of SqlServer Stored Procedure

What is a stored procedure?

The stored procedure in T-SQL is very similar to the method in the net language, and it can be called repeatedly. After the stored procedure is executed once, the statement can be cached so that the statement in the cache is used directly when it is executed next time.

This can improve the performance of the stored procedure.

  1. A stored procedure Procedure is a set of SQL statements to complete a specific function. It is compiled and stored in the database. The user executes it by specifying the name of the stored procedure and giving parameters.
  2. The stored procedure can contain logic control statements and data manipulation statements. It can accept parameters, output parameters, return single or multiple result sets, and return values.
  3. Because the stored procedure is compiled on the database server and stored in the database when it is created, the stored procedure runs faster than a single SQL statement block.
  4. At the same time, since only the stored procedure name and necessary parameter information are provided when calling, it can also reduce network traffic and simple network burden to a certain extent.
    Insert picture description here
    Insert picture description here

Advantages of stored procedures

1. Stored procedures allow standard component programming

After the stored procedure is created, it can be called and executed multiple times in the program without having to rewrite the SQL statement of the stored procedure.
And database professionals can modify the stored procedure at any time, but it has no effect on the source code of the application, which greatly improves the portability of the program.

2. The stored procedure can achieve faster execution speed

If an operation contains a large amount of T-SQL statement code and is executed multiple times, the stored procedure is much faster than batch execution.
Because the stored procedure is pre-compiled, when a stored procedure is run for the first time, the query optimizer analyzes and optimizes it, and gives the storage plan that is finally stored in the system table.
The batch T-SQL statement needs to be pre-compiled and optimized every time it runs, so the speed is slower.

3. The stored procedure reduces network traffic

For the same operation on a database object, if the T-SQL statement involved in this operation is organized into a stored procedure,
then when the stored procedure is called on the client, only the calling statement is passed on the network, otherwise it will It is a number of SQL statements.
Thereby reducing the network traffic and reducing the network load.

4. Stored procedures can be fully utilized as a security mechanism

The system administrator can restrict the authority of a certain stored procedure to be executed, so as to restrict access to certain data, avoid unauthorized users from accessing the data, and ensure the security of the data.

Insert picture description here

Disadvantages of stored procedures

1. Running speed

For very simple SQL, there is no advantage in the running speed of the stored procedure.

2. The code is poorly readable and not easy to maintain

The development and debugging of stored procedures is more difficult than ordinary programs (older versions of DB2 can only write stored procedures in C, which is even more a disaster).
The code is poorly readable and not easy to maintain.

3, transplantability difference

Because stored procedures bind applications to SQL Server, using stored procedures to encapsulate business logic will limit the portability of applications.
If application portability is very important in your environment, encapsulating business logic in a middle tier that is not specific to RDBMS may be a better choice.

The basic syntax of stored procedures

Variable declaration:
when declaring a variable, you must add the @ symbol
declare @num int before the variable

Variable assignment:
set
set @num= 30 must be added before the variable when assigning a variable

Declare multiple variables:
declare @name varchar(10),@num int

The use of if statement:

declare @d int
set @d = 1
IF @d = 1
BEGIN
    PRINT '正确' 
END 
ELSE BEGIN 
    PRINT '错误' 
END

Multi-conditional selection statement:

declare @today int
declare @week nvarchar(3)
set @today=3
set @week= case
     when @today=1 then '星期一'
     when @today=2 then '星期二'
     when @today=3 then '星期三'
     when @today=4 then '星期四'
     when @today=5 then '星期五'
     when @today=6 then '星期六'
     when @today=7 then '星期日'
     else '值错误'
end
print @week

loop statement:

DECLARE @i INT
SET @i = 1
WHILE @i<1000000 BEGIN
set @i=@i+1
END

Define the cursor:

DECLARE @cur1 CURSOR FOR SELECT .........

OPEN @cur1
FETCH NEXT FROM @cur1 INTO 变量
WHILE(@@FETCH_STATUS=0)
BEGIN
处理.....
FETCH NEXT FROM @cur1 INTO 变量
END
CLOSE @cur1
DEALLOCATE @cur1

Classification of stored procedures

1. System stored procedures

System stored procedures are stored procedures created by the system, whose purpose is to conveniently query information from system tables or complete management tasks related to updating database tables or other system management tasks.
The system stored procedures are mainly stored in the master database, the stored procedures beginning with the "sp" underscore.
Although these system stored procedures are in the master database, we can still call system stored procedures in other databases.
Some system stored procedures will be automatically created in the current database when a new database is created.

1.1, system stored procedure sql example

--表重命名
exec sp_rename 'stu', 'stud';--列重命名
exec sp_rename 'stud.name', 'sName', 'column';
exec sp_help 'stud';
--重命名索引
exec sp_rename N'student.idx_cid', N'idx_cidd', N'index';
exec sp_help 'student';

--查询所有存储过程
select * from sys.objects where type = 'P';
select * from sys.objects where type_desc like '%pro%' and name like 'sp%';

2. Custom stored procedures

The so-called custom stored procedure refers to a set of statements edited by t-sql in the user database in order to complete a specific functional requirement. In the user-defined process, there can be input parameters, returned output parameters and return to Client information and results.
If the "##" symbol is added in front of the stored procedure name, it means that the created stored procedure is temporary and global;
if the preceding is the "#" symbol, it means that the created stored procedure is temporary and local, and the stored procedure Can only be used in the session in which it was created.
After the above two stored procedures are created, they are stored in the tempdb database.
User-defined stored procedures can also be subdivided into t-sql language stored procedures and CLR stored procedures. CLR stored procedure refers to a stored procedure edited using the common language of the .NET framework. It can not only accept parameters provided by the user but also return the running result of the stored procedure. It is usually used as a public static method of a certain class.

2.1, create a stored procedure without parameters

--创建一个返回结果集的存储过程(proc或者procedure均可)
if (object_id('proc_get_student', 'P') is not null)--判断存储过程是否存在 另外一种 if (exists (select * from sys.objects where name = 'proc_get_student'))//
drop proc proc_get_student --删除存储过程
go
create proc proc_get_student --创建存储过程
as
select * from student; --结果集

--调用执行存储过程,得到返回集(exec或者execute均可)
exec proc_get_student;

2.2, modify the stored procedure

--修改存储过程
alter proc proc_get_student
as
select * from student;  --修改后的SQL语句

--调用执行存储过程,得到返回集(exec或者execute均可)
exec proc_get_student;

2.3. Stored procedure with parameters

--创建一个返回结果集的存储过程(proc或者procedure均可)
if (object_id('proc_find_stu', 'P') is not null)--判断存储过程是否存在
drop proc proc_find_stu
go
create proc proc_find_stu(@startId int, @endId int)--两个参数
as
select * from student where id between @startId and @endId   --查询语句
go

--调用执行存储过程,2,4为参数
exec proc_find_stu 2, 4;

2.4. Stored procedure with wildcard parameter

--创建一个返回结果集的存储过程(proc或者procedure均可)
if (object_id('proc_findStudentByName', 'P') is not null)
drop proc proc_findStudentByName
go
create proc proc_findStudentByName(@name varchar(20) = '%j%', @nextName varchar(20) = '%')
as
select * from student where name like @name and name like @nextName;
go

--调用执行存储过程
exec proc_findStudentByName;
exec proc_findStudentByName '%o%', 't%';

2.5. Stored procedure with output parameters

--创建一个返回结果集的存储过程(proc或者procedure均可)
if (object_id('proc_getStudentRecord', 'P') is not null)
drop proc proc_getStudentRecord
go
create proc proc_getStudentRecord(
@id int, --默认输入参数
@name varchar(20) out, --输出参数
@age varchar(20) output--输入输出参数
)
as
select @name = name, @age = age from student where id = @id and sex = @age;
go

--调用执行存储过程
declare @id int,
@name varchar(20),
@temp varchar(20);
set @id = 7;
set @temp = 1;
exec proc_getStudentRecord @id, @name out, @temp output;
select @name, @temp;
print @name '#' @temp;

3. Extended stored procedures

Usually identified with "xp_" as the prefix, the function is realized by executing dynamic link library, that is, DLL file, outside the sql server system. The stored procedure is often edited using the API interface and can be loaded into the address space of the sql server instance. Trial run.

Common extended stored procedures in sql server are:

  • xp_enumgroups Specifies the WINDOWS local group list. The global group table defined in the WINDOWS domain xp_findnextmsg
  • Accept the input mail ID number, and return the output mail ID number xp_grantlogin to assign the user permission to the sql server2012 system
  • xp_logevent Input user-defined messages into sql server log file or Windows system event viewer
  • xp_loginconfig displays the security configuration of login when the sql server 2012 instance is running

Okay, let’s stop here,

Bye bye, see you next time.


Welcome to follow and subscribe to my WeChat public platform [Xiong Ze has something to say], more fun and easy-to-learn knowledge waiting for you

Author: Xiong Ze - bitter learning music with
the public number: Bear Ze something to say
Source 1: https://www.cnblogs.com/xiongze520/p/14595601.html
Source 2: https://blog.csdn.net /qq_35267585/article/details/115324181 It
is not easy to create. Any person, group or organization reprints or partially reprints or extracts, please indicate the author and the original link in an obvious place in the article.
Insert picture description here

Guess you like

Origin blog.csdn.net/qq_35267585/article/details/115324181