The difference between triggers, stored procedures and functions

What is the difference between triggers, stored procedures and functions? (Turn)
Trigger is a special stored procedure, the stored procedure needs to be called by the program, and the trigger will be executed automatically; the function you mentioned is a custom function, the function generates output according to the input, and the custom is only the relationship between input and output Defined by the user. When to use triggers? The system is required to automatically complete related tasks according to certain operations, such as automatically deducting the inventory of the product according to the input quantity of the product that is bought. When to use stored procedures? A stored procedure is a program. It is a SQL statement that has been grammatically checked and compiled, so it runs extremely fast.

The specific difference between stored procedures and user-defined functions

Look at the definition first:

Stored procedure

Stored procedures can make the management of the database and the work 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. The stored procedure is stored in the database and can be executed by the application through a call, and allows the user to declare variables, conditional execution and other powerful programming functions.

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.

You can use stored procedures for any purpose using SQL statements, and it has the following advantages:

A series of SQL statements can be executed in a single stored procedure.

You can reference other stored procedures from within your own stored procedures, which can simplify a series of complex statements.

The stored procedure is compiled on the server when it is created, so it executes faster than a single SQL statement.

User-defined function

A function is a subroutine composed of one or more Transact-SQL statements, which can be used to encapsulate code for reuse. Microsoft? SQL Server? 2000 does not restrict users to the built-in functions defined as part of the Transact-SQL language, but allows users to create their own user-defined functions.

You can use the CREATE FUNCTION statement to create, use the ALTER FUNCTION statement to modify, and use the DROP FUNCTION statement to remove user-defined functions. Each fully legal user-defined function name (database_name.owner_name.function_name) must be unique.

You must be granted CREATE FUNCTION permission to create, modify, or remove user-defined functions. Before a user who is not the owner can use a function in a Transact-SQL statement, the user must first be granted the appropriate permissions for the function. To create or change tables that reference user-defined functions in CHECK constraints, DEFAULT clauses, or calculated column definitions, you must also have REFERENCES permissions for the functions.

In the function, the differential processing results in a Transact-SQL error that deletes the statement and continues to the next statement in a mode such as a trigger or a stored procedure. In the function, the above error will cause the execution of the function to stop. The next operation causes the statement that called the function to stop waking up.

Types of user-defined functions

SQL Server 2000 supports three user-defined functions:

  1. Scalar function

  2. Built-in table-valued functions

  3. Multi-statement table-valued functions

User-defined functions take zero or more input parameters and return scalar values ​​or tables. The function can have up to 1024 input parameters. When a function parameter has a default value, the default DEFAULT keyword must be specified when calling the function to get the default value. This behavior is different from a parameter that contains a default value in a stored procedure, and omitting the function in these stored procedures also means omitting the default value. User-defined functions do not support output parameters.

Scalar functions return a single data value of the type defined in the RETURNS clause. All scalar data types can be used, including bigint and sql_variant. Timestamp data types, user-defined data types, and non-scalar types (such as table or cursor) are not supported. The body of the function defined in the BEGIN...END block contains the series of Transact-SQL statements that return the value. The return type can be any data type except text, ntext, image, cursor, and timestamp.

Table-valued functions return table. For embedded table-valued functions, there is no function body; the table is the result set of a single SELECT statement. For multi-statement table-valued functions, the body of the function defined in the BEGIN...END block contains Transact-SQL statements that can generate rows and insert rows into the returned table. For more information about embedded table-valued functions, see Embedded User-Defined Functions. For more information about table-valued functions, see User-defined functions that return table data types.

The statements in the BEGIN...END block cannot have any side effects. Function side effects are any permanent changes to the state of resources that have scope outside the function (for example, modification of database tables). The only changes that can be made to statements in a function are changes to local objects (such as local cursors or local variables) on the function. Operations that cannot be performed in a function include: modifying database tables, operating on partial cursors that are not on the function, sending emails, trying to modify the directory, and generating a result set that is returned to the user.

The valid statement types in the function include:

  1. DECLARE statement, which can be used to define local data variables and cursors in a function.

  2. Assign values ​​to function local objects, such as using SET to assign values ​​to scalar and table local variables.

  3. Cursor operations, which refer to the local cursors declared, opened, closed, and released in the function. The FETCH statement is not allowed to return data to the client. Only the FETCH statement is allowed to assign values ​​to local variables through the INTO clause.

  4. Control flow statement.

  5. The SELECT statement contains a select list with expressions that assign values ​​to local variables of the function.

  6. INSERT, UPDATE and DELETE statements, these statements modify the local table variables of the function.

  7. EXECUTE statement, which calls an extended stored procedure.

The actual number of executions of the function specified in the query may vary among the execution plans generated by the optimizer. The example is the function called by the subquery in the WHERE clause. The number of times the subquery and its function are executed will vary depending on the access path chosen by the optimizer.

User-defined functions are not allowed to use built-in functions that return different data for each call. The following built-in functions are not allowed in user-defined functions:
Insert picture description here

Schema binding function

CREATE FUNCTION supports the SCHEMABINDING clause, which can bind the function to the schema of any object it references (such as tables, views, and other user-defined functions). Attempts to ALTER or DROP any objects referenced by the schema binding function will fail.

The following conditions must be met to specify SCHEMABINDING in CREATE FUNCTION:

  1. All views and user-defined functions referenced by this function must be bound to the schema.

  2. All objects referenced by the function must be in the same database as the function. You must use a one-part or two-part name to refer to an object.

  3. You must have REFERENCES permission on all objects (tables, views, and user-defined functions) referenced in the function.

You can use ALTER FUNCTION to delete the schema binding. The ALTER FUNCTION statement will redefine the function by specifying the function without WITH SCHEMABINDING.

Call user-defined function

When calling a scalar user-defined function, you must provide a name consisting of at least two parts:

SELECT *, MyUser.MyScalarFunction()FROM MyTable
can call table-valued functions using a partial name:

SELECT *FROM MyTableFunction()
However, when calling a SQL Server built-in function that returns a table, the prefix :: must be added to the function name:

SELECT * FROM ::fn_helpcollations()
can refer to a scalar function at any position where the expression of the same data type returned by a function allowed in a Transact-SQL statement is located, including calculated columns and CHECK constraint definitions. For example, the following statement creates a simple function that returns decimal:

CREATE FUNCTION CubicVolume-- Input dimensions in centimeters (@CubeLength decimal(4,1), @CubeWidth decimal(4,1), @CubeHeight decimal(4,1) )RETURNS decimal(12,3) – Cubic Centimeters.ASBEGIN RETURN (@CubeLength * @CubeWidth * @CubeHeight )END
Then you can use the function anywhere that allows integer expressions (such as in the calculated column of a table):

CREATE TABLE Bricks (BrickPartNmbr int PRIMARY KEY, BrickColor nchar(20), BrickHeight decimal(4,1), BrickLength decimal(4,1), BrickWidth decimal(4,1), BrickVolume AS (dbo.CubicVolume(BrickHeight, BrickLength, BrickWidth)))
dbo.CubicVolume is an example of a user-defined function that returns a scalar value. The RETURNS clause defines the scalar data type of the value returned by the function. The BEGIN...END block contains one or more Transact-SQL statements that execute the function. Each RETURN statement in this function must have a parameter that can return a data value with the data type specified in the RETURNS clause (or can be implicitly converted to the data type of the type specified in RETURNS). The value of the RETURN parameter is the value returned by the function.

Guess you like

Origin blog.csdn.net/AnameJL/article/details/111410667