[Database Principle] Stored Procedure

Overview of stored procedures.

The ultimate goal of people using SQL Server database to store data is to develop various application software to process and manage these data. Only T-SQL statements can perform operations on SQL Server database, so various front-end development tools, such as VB, C# , Java, etc. all perform operations on the database by calling T-SQL statements, and its own programming syntax elements are used to complete input/output and programming logic.
The T-SQL statement in the program is finally compiled and executed by the execution engine on the SQL Server server. Each time the program calls a T-SQL statement, the execution engine must first compile and then execute it. At this time, if there are many concurrent users operating on the SQL Server database at the same time, the execution efficiency of such T-SQL statements is extremely low. The reasons for this situation are as follows:

  • The T-SQL statement is stored in the application. The SQL Server server passively executes the T-SQL statement. It does not know in advance what T-SQL statement the client will execute, so it can only be compiled and executed each time.
  • Application programs can only execute T-SQL statements sentence by sentence. Therefore, when there are more complex T-SQL programs, a large amount of traffic will be generated on the network, and the execution efficiency will be very low.

In order to solve this problem, SQL Server puts forward the concept of stored procedure, which has caused a revolution in database application development technology. At present, mainstream network database systems such as SQL Server and Oracle support stored procedure technology.
Stored Procedure is a compiled object stored in the SQL Server database. It is a set of SQL statements to complete specific functions. This statement set is compiled and stored in the database, and can be managed by client tools and applications As well as other stored procedure calls, parameters can be passed at the same time, we can completely understand the stored procedure as a subroutine. The advantages of introducing stored procedures are as follows:

  • [Modular programming] Like the function concept in many high-level languages, the created stored procedure is stored in the database to which it belongs, and can be called at will in the future, and can be modified independently of the source code.
  • [Efficient execution] When a stored procedure is created, SQL Server compiles, analyzes and optimizes it. After being executed for the first time, the stored procedure will remain in the memory of the server. When the procedure is called again, the code in the memory can be directly called for execution, which greatly improves the execution speed.
  • [Reduce network traffic] A T-SQL code that may require hundreds of statements can be replaced by a statement that executes a stored procedure.
  • [Use as a security mechanism] Users who do not have the authority to execute certain statements can be granted the authority to execute stored procedures, so that these users can implement functions under restrictions without having to have excessive permissions.

Stored procedures can be divided into the following three categories:

  • [System Stored Procedure] is a stored procedure provided by the SQL Server system by default. It is mainly stored in the master database and sp_starts with a prefix . The system stored procedure mainly syscommentsobtains information from the system tables , and provides support for the system administrator to manage the SQL Server. With the help of system stored procedures, many administrative or informational activities in SQL Server, such as understanding database objects and database information, can be completed smoothly and effectively. Although these system stored procedures are stored in the master database, they can still be called in other databases without adding a database name.
  • [Custom stored procedure] is created by the user (program developer or DBA), used to complete a certain function of the stored procedure.
  • [Extended stored procedure] A stored procedure used to extend the functionality of the SQL Server server, and its name xp_starts with a prefix .

Create a stored procedure.

T-SQL provides CREATE PROCEDUREstatements to create a stored procedure. Before giving the created grammar and examples, there are 4 quasi-tests to note:

  1. In a batch, the CREATE PROCEDUREstatement cannot be combined with other SQL statements;
  2. The owner of the database has the default permission to create stored procedures, and it can pass the permission to other users;
  3. The stored procedure is a database object, and its naming must conform to the specification;
  4. Only stored procedures belonging to the current database can be created in the current database.

[Example] In the Teachdatabase, create a MyProcstored procedure named without parameters, the function of the stored procedure is Sto query the information of all male students from the data table .

USE Teach
GO
CREATE PROCEDURE MyProc 
AS SELECT * FROM S WHERE Sex='男'

A stored procedure without parameters only needs to be given a name.

[Example] Define a stored procedure with parameters. In the Teachdatabase, create a InsertRecordstored procedure named . The function of the stored procedure is to Sinsert a record into the data table, and the value of the new record is provided by the parameter.

USE Teach
GO
CREATE PROCEDURE InsertRecord
( 
	@sno VARCHAR(6),
	@sn NVARCHAR(10),
	@sex NCHAR(1),
	@age INT,
	@dept NVARCHAR(20)
)
AS
INSERT INTO S VALUES(@sno,@sn,@sex,@age, @dept)

Stored procedures with parameters need to give formal parameter definitions after the procedure name.

[Example] Define a stored procedure with parameter default values. In the Teachdatabase, create a name for the InsertRecordDefastored procedure, function of the stored procedure is to Sinsert a record in the data table, the value of the new record is provided by the parameter, if the other system is not provided Deptwhen the value is replaced by the parameter's default value.

USE Teach
GO
CREATE PROCEDURE InsertRecordDefa
( 
	@sno VARCHAR(6),
	@sn NVARCHAR(10),
	@sex NCHAR(1),
	@age INT,
	@dept NVARCHAR(20)= '无'
)
AS
INSERT INTO S VALUES(@sno, @sn, @sex, @age, @dept)

The usage of the default parameters is consistent with the C language, just give the default values.

[Example] Define a stored procedure that can return a value. In the Teachdatabase, create a QueryTeachstored procedure named . The function of the stored procedure is Sto query the name and department of a student from the data table according to the student number, and the result of the query is returned by the parameters @snand the department @dept.

USE Teach
GO
CREATE PROCEDURE QueryTeach
( 
	@sno VARCHAR(6),
	@sn NVARCHAR(10) OUTPUT,
	@dept NVARCHAR(20) OUTPUT
)
AS
SELECT @sn=SN,@dept=Dept
FROM S
WHERE SNo=@sno

Need to be the parameter of the return value, add keywords OUTPUT.

After seeing the above 4 examples, we give the syntax format for creating a stored procedure:

CREATE PROCEDURE NAME_OF_PROCEDURE
AS sql_statement [,...n ]

Execute the stored procedure.

EXEC NAME_OF_PROCEDURE

[Example] Execute the stored procedure MyProc without parameters defined in the database Teach.

USE Teach
GO
EXEC MyProc

View the stored procedure code.

EXEC sp_helptext NAME_OF_PROCEDURE

[Example] View the source code of the stored procedure MyProc in the database Teach.

USE Teach
GO
EXEC sp_helptext MyProc

Delete the stored procedure.

DROP PROCEDURE NAME_OF_PROCEDURE

[Example] Delete the stored procedure MyNewProc from the database Teach, assuming that MyNewProc already exists.

USE Teach
GO
DROP PROCEDURE MyNewProc

Guess you like

Origin blog.csdn.net/weixin_44246009/article/details/108126051