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!

This article explores optimizing MySQL memory usage in Docker. It discusses monitoring techniques (Docker stats, Performance Schema, external tools) and configuration strategies. These include Docker memory limits, swapping, and cgroups, alongside

This article addresses MySQL's "unable to open shared library" error. The issue stems from MySQL's inability to locate necessary shared libraries (.so/.dll files). Solutions involve verifying library installation via the system's package m

The article discusses using MySQL's ALTER TABLE statement to modify tables, including adding/dropping columns, renaming tables/columns, and changing column data types.

This article compares installing MySQL on Linux directly versus using Podman containers, with/without phpMyAdmin. It details installation steps for each method, emphasizing Podman's advantages in isolation, portability, and reproducibility, but also

This article provides a comprehensive overview of SQLite, a self-contained, serverless relational database. It details SQLite's advantages (simplicity, portability, ease of use) and disadvantages (concurrency limitations, scalability challenges). C

This guide demonstrates installing and managing multiple MySQL versions on macOS using Homebrew. It emphasizes using Homebrew to isolate installations, preventing conflicts. The article details installation, starting/stopping services, and best pra

Article discusses configuring SSL/TLS encryption for MySQL, including certificate generation and verification. Main issue is using self-signed certificates' security implications.[Character count: 159]

Article discusses popular MySQL GUI tools like MySQL Workbench and phpMyAdmin, comparing their features and suitability for beginners and advanced users.[159 characters]


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

EditPlus Chinese cracked version
Small size, syntax highlighting, does not support code prompt function

Dreamweaver Mac version
Visual web development tools

ZendStudio 13.5.1 Mac
Powerful PHP integrated development environment

SublimeText3 Mac version
God-level code editing software (SublimeText3)

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),
