search
HomeDatabaseMysql TutorialWrite functions and stored procedures in SQL Server

在 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. If there is any infringement, please contact admin@php.cn delete
Explain the InnoDB Buffer Pool and its importance for performance.Explain the InnoDB Buffer Pool and its importance for performance.Apr 19, 2025 am 12:24 AM

InnoDBBufferPool reduces disk I/O by caching data and indexing pages, improving database performance. Its working principle includes: 1. Data reading: Read data from BufferPool; 2. Data writing: After modifying the data, write to BufferPool and refresh it to disk regularly; 3. Cache management: Use the LRU algorithm to manage cache pages; 4. Reading mechanism: Load adjacent data pages in advance. By sizing the BufferPool and using multiple instances, database performance can be optimized.

MySQL vs. Other Programming Languages: A ComparisonMySQL vs. Other Programming Languages: A ComparisonApr 19, 2025 am 12:22 AM

Compared with other programming languages, MySQL is mainly used to store and manage data, while other languages ​​such as Python, Java, and C are used for logical processing and application development. MySQL is known for its high performance, scalability and cross-platform support, suitable for data management needs, while other languages ​​have advantages in their respective fields such as data analytics, enterprise applications, and system programming.

Learning MySQL: A Step-by-Step Guide for New UsersLearning MySQL: A Step-by-Step Guide for New UsersApr 19, 2025 am 12:19 AM

MySQL is worth learning because it is a powerful open source database management system suitable for data storage, management and analysis. 1) MySQL is a relational database that uses SQL to operate data and is suitable for structured data management. 2) The SQL language is the key to interacting with MySQL and supports CRUD operations. 3) The working principle of MySQL includes client/server architecture, storage engine and query optimizer. 4) Basic usage includes creating databases and tables, and advanced usage involves joining tables using JOIN. 5) Common errors include syntax errors and permission issues, and debugging skills include checking syntax and using EXPLAIN commands. 6) Performance optimization involves the use of indexes, optimization of SQL statements and regular maintenance of databases.

MySQL: Essential Skills for Beginners to MasterMySQL: Essential Skills for Beginners to MasterApr 18, 2025 am 12:24 AM

MySQL is suitable for beginners to learn database skills. 1. Install MySQL server and client tools. 2. Understand basic SQL queries, such as SELECT. 3. Master data operations: create tables, insert, update, and delete data. 4. Learn advanced skills: subquery and window functions. 5. Debugging and optimization: Check syntax, use indexes, avoid SELECT*, and use LIMIT.

MySQL: Structured Data and Relational DatabasesMySQL: Structured Data and Relational DatabasesApr 18, 2025 am 12:22 AM

MySQL efficiently manages structured data through table structure and SQL query, and implements inter-table relationships through foreign keys. 1. Define the data format and type when creating a table. 2. Use foreign keys to establish relationships between tables. 3. Improve performance through indexing and query optimization. 4. Regularly backup and monitor databases to ensure data security and performance optimization.

MySQL: Key Features and Capabilities ExplainedMySQL: Key Features and Capabilities ExplainedApr 18, 2025 am 12:17 AM

MySQL is an open source relational database management system that is widely used in Web development. Its key features include: 1. Supports multiple storage engines, such as InnoDB and MyISAM, suitable for different scenarios; 2. Provides master-slave replication functions to facilitate load balancing and data backup; 3. Improve query efficiency through query optimization and index use.

The Purpose of SQL: Interacting with MySQL DatabasesThe Purpose of SQL: Interacting with MySQL DatabasesApr 18, 2025 am 12:12 AM

SQL is used to interact with MySQL database to realize data addition, deletion, modification, inspection and database design. 1) SQL performs data operations through SELECT, INSERT, UPDATE, DELETE statements; 2) Use CREATE, ALTER, DROP statements for database design and management; 3) Complex queries and data analysis are implemented through SQL to improve business decision-making efficiency.

MySQL for Beginners: Getting Started with Database ManagementMySQL for Beginners: Getting Started with Database ManagementApr 18, 2025 am 12:10 AM

The basic operations of MySQL include creating databases, tables, and using SQL to perform CRUD operations on data. 1. Create a database: CREATEDATABASEmy_first_db; 2. Create a table: CREATETABLEbooks(idINTAUTO_INCREMENTPRIMARYKEY, titleVARCHAR(100)NOTNULL, authorVARCHAR(100)NOTNULL, published_yearINT); 3. Insert data: INSERTINTObooks(title, author, published_year)VA

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Tools

mPDF

mPDF

mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),

SublimeText3 English version

SublimeText3 English version

Recommended: Win version, supports code prompts!

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Dreamweaver Mac version

Dreamweaver Mac version

Visual web development tools

VSCode Windows 64-bit Download

VSCode Windows 64-bit Download

A free and powerful IDE editor launched by Microsoft