Brief Analysis of Database Stored Procedures and Functions


Stored procedure:

Stored procedures can make the management of a database and the job of displaying information about the database and its users much easier. A stored procedure is a precompiled collection of SQL statements and optional control flow statements, stored under a name and processed as a unit. Stored procedures are stored in the database, can be executed by an application with a single call, and allow the user to declare variables, conditional execution, and other powerful programming features.

Stored procedures can contain program flow, logic, and queries to the database. They can accept parameters, output parameters, return single or multiple result sets, and return values.

Stored procedures can be used for any purpose using SQL statements and have the following advantages:

  1. A series of SQL statements can be executed within a single stored procedure.
  2. You can reference other stored procedures from within your own stored procedure, which simplifies a series of complex statements.
  3. Stored procedures are compiled on the server when they are created, so they execute faster than a single SQL statement.

User-defined function:

Microsoft SQL Server 2000 allows the creation of user-defined functions. Like any function, a user-defined function is a routine that returns a value. Depending on the type of value returned, each user-defined function can be divided into the following three categories:

  1. Functions That Return Updatable Data Tables
    If a user-defined function contains a single SELECT statement and the statement is updatable, the results returned by the function in tabular format can also be updated.

  2. Functions that return non-updatable data tables
    If a user-defined function contains more than one SELECT statement, or contains a non-updatable SELECT statement, the table-format results returned by the function are also non-updatable.

  3. Functions that return scalar
    values ​​User-defined functions can return scalar values.

the difference:

  1. Generally speaking, the functions implemented by stored procedures are more complex, while the functions implemented by functions are more targeted.
  2. For stored procedures, parameters can be returned, while functions can only return values ​​or table objects.
  3. Stored procedures are generally executed as a separate part, while functions can be called as part of a query statement. Since a function can return a table object, it can be located after the FROM keyword in a query statement.
  4. 当存储过程和函数被执行的时候,SQL Manager会到procedure cache中去取相应的查询语句,如果在procedure cache里没有相应的查询语句,SQL Manager就会对存储过程和函数进行编译。

【注】

sql语句执行的时候要先编译,然后执行。
存储过程(Stored Procedure)是一组为了完成特定功能的SQL语句集,经编译后存储在数据库中。用户通过指定存储过程的名字并给出参数(如果该存储过程带有参数)来执行它。存储过程是数据库中的一个重要对象,任何一个设计良好的数据库应用程序都应该用到存储过程

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325482704&siteId=291194637