Home  >  Article  >  Database  >  Write functions and stored procedures in SQL Server

Write functions and stored procedures in SQL Server

王林
王林forward
2023-09-16 15:13:02580browse

在 SQL Server 中编写函数和存储过程

A collection of SQL statements contained in stored procedures and functions, database objects used to perform certain tasks (or can also be used in data science). The two differ in many ways.

In this article, we will discuss functions and procedures in detail and their differences.

Let’s start with stored procedures -

Stored procedures in SQL

Simple written SQL code is saved for reuse multiple times, thus forming a stored procedure. If you can think of a query that you write frequently, you can save it as a stored procedure and then call that stored procedure to run the SQL code you saved as part of the stored procedure. This will save you from having to write the same questions over and over again.

You can repeatedly execute the same SQL code and provide parameters to the stored procedure. As needed, the stored procedure will respond appropriately based on the supplied parameter values.

Performance can also be enhanced through stored procedures. A set of SQL statements is used to perform multiple tasks. Which SQL statements are run next depends on the results of the initial SQL statement and conditional logic. These SQL statements and the conditional logic they contain can be combined into a single execution plan on the server by writing them into a stored procedure. Since all work is performed on the server, conditional logic can be performed without passing the results to the client.

Advantages of stored procedures

Compile and execute

Each stored procedure is compiled once by SQL Server and then the execution plan is reused. When calling stored procedures frequently, the performance improvements are huge.

Client/server traffic reduction

If network bandwidth is an issue in your environment, you'll be pleased to know that stored procedures can compress lengthy SQL searches into a single line that can be transmitted over the wire.

Efficient code reuse and programming abstraction

Stored procedures are available to many user and client applications. If you use them in a planned way, it will take less time to complete the development cycle.

Strengthen security measures

Independent of permissions on the underlying tables, you can provide users with access permissions to run stored procedures.

Functions in SQL

SQL Server supports two types of functions

Built-in functions

Built-in functions operate according to the Transact-SQL reference definition and cannot be changed. Only Transact-SQL statements that follow the syntax established by the Transact-SQL reference can use these functions as a reference.

The system has already defined these functions. It is divided into two categories -

In this tutorial, we will refer to the following table -

ID

Name

mark

age

1

severe

90

19

2

suresh

50

20

3

pratik

80

twenty one

4

Danraj

95

19

5

Ram

85

18

Scalar function

These operations take a value as input and output it. Some system scalar operations include -

  • round() - Rounds a number to the nearest three digits. For example, round(28.64851) will produce 28.649

SELECT ROUND(MARKS,0) FROM students;
  • upper() - upper("english") returns English, lower("ENGLISH") returns English.

SELECT upper(NAME) FROM Students;

Output

HARSH
SURESH
PRATIK
DHANRAJ
RAM
  • rand() - Using the function rand(), a random number in a range will be returned. For example, Rand(8), returns 0.71372242401 or any other randomly generated number.

System aggregate function

These functions return a single value, these functions take a collection of input parameters. Examples include -

Avg() Will provide an average value for all provided inputs.

Example

SELECT AVG(MARKS) FROM Students;

Output

80

Count() This function will return the number of rows that meet the given criteria.

Example

SELECT COUNT(*) FROM Students;

Output

5

Max() and min() The functions max() and min() will return the highest and lowest value among the supplied arguments.

Example

SELECT MAX(AGE) FROM Students

Output

21

Example

SELECT MIN(AGE) FROM Students;

Output

18

User-defined functions

Use the CREATE FUNCTION command to create a custom Transact-SQL function. User-defined functions provide a single value and require zero to more input parameters. Some user-defined functions (UDFs) return a single data value, such as a decimal number, character, or int.

Scalar operations

User-defined scalar functions output a value for each step of the function operation. Returns any data type value in the function.

Table-valued functions

Inline functions

Inline table functions with user-defined values ​​perform operations and return the results as a table. There is no BEGIN/END body. Just use a SELECT statement to get the results.

Multi-statement function

If a user-defined function contains an unmodifiable SELECT statement or contains multiple SELECT statements, the results it gives will not change. We must explicitly specify table variables and describe the values ​​that can be retrieved from various SQL queries.

Advantages of user-defined functions

  • Support modular programming

  • The function can be created once, saved in the database, and then used as many times in the software as you need. User-defined functions can be changed without changing the application's source code.

  • They can speed up execution

  • Transact-SQL user-defined functions, such as stored procedures, reduce compilation costs by caching plans and reusing them across multiple executions. Because user-defined functions do not need to be reparsed and optimized every time they are used, execution time is significantly reduced.

  • For computational workloads, business logic, and string operations, CLR functions perform significantly better than Transact-SQL functions. Data access-intensive logic is better suited for Transact-SQL operations.

  • They may reduce network activity.

  • Functions can be used to represent operations that filter information based on complex constraints that cannot be represented by a single numeric expression. To reduce the number of rows served to the client, this function can be used in the WHERE clause.

The difference between user-defined functions and stored procedures

The following table highlights the main differences between user-defined functions and stored procedures in SQL -

standard

User-defined function

Stored Procedure

return value

Single value

Single, multiple or even zero

parameter

input value

Input and output values

database

Cannot be modified

Can be modified

statement

SELECT statement only

SELECT and DML statements

call

Call from procedure

Cannot be called from function

Compile and execute

Need to compile every time

Only compile once

Transaction Management

impossible

impossible

in conclusion

In this article, we discussed in depth about stored procedures and their advantages, functions, types of functions, and advantages of functions, and finally came to the difference between functions and stored procedures.

The above is the detailed content of Write functions and stored procedures in SQL Server. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:tutorialspoint.com. If there is any infringement, please contact admin@php.cn delete