Functions vs stored procedures in SQL Server

Functions vs stored procedures in SQL Server

Functions vs stored procedures in SQL Server

SQLShack

SQL Server training Español

Functions vs stored procedures in SQL Server

February 14, 2017 by Daniel Calbimonte

Introduction

Usually DBAs prefer stored procedures in SQL instead of functions in SQL Server. Is this a good practice? In this article, we will teach how to create stored procedures and functions in SQL Server and show advantages and disadvantages one of each. In our examples, we will use scalar user defined functions aka UDFs. We will show some Table-Valued Functions in the future. CLR functions will not be covered here. We will include the following topics: Creating a hello world in a stored procedure vs a function Invoking a stored procedure vs invoking a function Using variables in a stored procedure vs a function Reusability Invoking functions/procedures inside functions/procedures

Getting started

1 Creating a hello world in a stored procedure in SQL vs a function

Let’s create a simple “Hello world” in a stored procedure and a function to verify which one is easier to create. We will first create a simple stored procedure using the print statement in SSMS: 12345 CREATE PROCEDURE HelloWorldprocedureASPRINT 'Hello World' Execute the code and then call the stored procedure in SQL: 123 exec HelloWorldprocedure If you execute the code, you will be able to see the “Hello World” message:
Figure 1. “Hello world” stored procedure result Now let’s try to do the same with a function: 12345678 CREATE FUNCTION dbo.helloworldfunction()RETURNS varchar(20)AS BEGIN RETURN 'Hello world'END We can call the function using a select: The function will return the following message:
Figure 2. “Hello world” using a function If you compare the code, the function requires more code to do the same thing. The BEGIN and END blocks are mandatory in a function while the stored procedure do not require them if it is just one line. In a function, it is mandatory to use the RETURNS and RETURN arguments, whereas in a stored procedure is not necessary. In few words, a stored procedure is more flexible to write any code that you want, while functions have a rigid structure and functionality.

2 Invoking a stored procedure in SQL vs invoking a function

You can invoke a stored procedure in different ways: 123456 exec HelloWorldprocedureexecute HelloWorldprocedureexecute dbo.HelloWorldprocedureHelloWorldprocedure You can invoke using exec or execute and even you can invoke the stored procedure without the execute statement. You do not necessarily need to specify the schema name. The functions are less flexible. You need to specify the schema to invoke it (which is a good practice to avoid conflicts with other object with the same name and different schema). Let’s call a function without the schema: 123 select helloworldfunction() as regards The message displayed is the following: Msg 195, Level 15, State 10, Line 20 ‘helloworldfunction’ is not a recognized built-in function name As you can see, the schema name is mandatory to invoke a function: 123 select dbo.helloworldfunction() as regards

3 Using variables in a stored procedure in SQL vs a function

We are going to convert Celsius degrees to Fahrenheit using stored procedures and functions to see the differences. Let’s start with a stored procedure: 123456 CREATE PROCEDURE CONVERTCELSIUSTOFAHRENHEIT@celsius realasselect @celsius*1.8+32 as Fahrenheit Celsius is the input parameter and we are doing the calculations in the select statement to convert to Fahrenheit degrees. If we invoke the stored procedure, we will verify the result converting 0 °C: 123 exec CONVERTCELSIUSTOFAHRENHEIT 0 The result will be 32 °F:
Figure 3. Stored procedure in SQL to convert Celsius to Fahrenheit Let’s try to do the same with a function: 123456789 CREATE FUNCTION dbo.f_celsiustofahrenheit(@celcius real)RETURNS realAS BEGIN RETURN @celcius*1.8+32END You can call the function created in the following way: 123 select dbo.f_celsiustofahrenheit(0) as fahrenheit We are converting 0 °C to °F. As you can see, the code is very simple in both cases.

4 Reusability

The main advantage about a function is that it can be reused in code. For example, you can do the following: 123 select CONCAT(dbo.helloworldfunction(),', welcome to sqlshack') Regards In this example, we are concatenating the function of the example 1 with a string. The result is the following:
Figure 4. Concatenating a string to a function As you can see, you can easily concatenate a function with a string. To do something similar with a stored procedure in SQL, we will need an output variable in a stored procedure to concatenate the output variable with a string. Let’s take a look to the stored procedure: 123456 create procedure outputparam@paramout varchar(20) outasselect @paramout='Hello world' The procedure is assigning the Hello Word string to an output parameter. You can use the out or output word to specify that the parameter is an output parameter. The code may be simple, but calling the procedure to use the output parameter to be concatenated is a little bit more complex than a function: 123456 declare @message varchar(20)exec outputparam @paramout=@message outselect @message as regardsselect CONCAT(@message,', welcome to sqlshack') As you can see, you need to declare a new variable named @message or any other name of your preference. When you call the stored procedure, you need to specify that it is an outer parameter. An advantage of the stored procedures is that you can have several parameters while in functions, you can return just one variable (scalar function) or one table (table-valued functions).

5 Invoke functions procedures inside functions Stored procedures in SQL

Can we invoke stored procedures inside a function? Let’s take a look: 12345678910 CREATE FUNCTION dbo.procedureinsidefunction()RETURNS varchar(22)AS BEGIN execute HelloWorldprocedure Declare @hellovar varchar(22)=', welcome to sqlshack' RETURN @hellovar END The function will invoke the HelloWorldprocedure created in the section 1. If we invoke the function, we will have the following message: Msg 557, Level 16, State 2, Line 65 Only functions and some extended stored procedures can be executed from within a function. As you can see, you cannot call a function from a stored procedure. Can you call a function from a procedure? Here it is the procedure: 12345 create procedure functioninsideprocedureasselect dbo.helloworldfunction() If we invoke the stored procedure in SQL, we will be able to check if it works or not: 123 exec functioninsideprocedure The result displayed is the following:
Figure 5. A function inside a procedure As you can see, you can invoke functions inside a stored procedure and you cannot invoke a stored procedure inside a function. You can invoke a function inside a function. The following code shows a simple example: 123456789 CREATE FUNCTION dbo.functioninsidefunction()RETURNS varchar(50)AS BEGIN RETURN dbo.helloworldfunction()END We can call the function as usual: 123 select dbo.functioninsidefunction() as regards Is it possible to call procedures inside other procedures? Yes, you can. Here you have an example about it: 12345 create procedure procedureinsideprocedureasexecute dbo.HelloWorldprocedure You can execute the procedure as usual: 123 exec dbo.procedureinsideprocedure

Conclusions

Stored procedures in SQL are easier to create and functions have a more rigid structure and support less clauses and functionality. By the other hand, you can easily use the function results in T-SQL. We show how to concatenate a function with a string. Manipulating results from a stored procedure is more complex. In a scalar function, you can return only one variable and in a stored procedure multiple variables. However, to call the output variables in a stored procedure, it is necessary to declare variables outside the procedure to invoke it. In addition, you cannot invoke procedures within a function. By the other hand, in a procedure you can invoke functions and stored procedures. Finally, it is important to mention some performance problems when we use functions. However, this disadvantage will be explained in a next article, Functions and stored procedures comparisons in SQL Server.

References

For more information, refer to these links: CREATE FUNCTION (Transact-SQL) CREATE PROCEDURE (Transact-SQL) CONCAT (Transact-SQL)
Author Recent Posts Daniel CalbimonteDaniel Calbimonte is a Microsoft Most Valuable Professional, Microsoft Certified Trainer and Microsoft Certified IT Professional for SQL Server. He is an accomplished SSIS author, teacher at IT Academies and has over 13 years of experience working with different databases.

He has worked for the government, oil companies, web sites, magazines and universities around the world. Daniel also regularly speaks at SQL Servers conferences and blogs. He writes SQL Server training materials for certification exams.

He also helps with translating SQLShack articles to Spanish

View all posts by Daniel Calbimonte Latest posts by Daniel Calbimonte (see all) SQL Partition overview - September 26, 2022 ODBC Drivers in SSIS - September 23, 2022 Getting started with Azure SQL Managed Instance - September 14, 2022

Related posts

An overview of sp_getapplock and sp_releaseapplock stored procedures Functions and stored procedures comparisons in SQL Server Partial stored procedures in SQL Server SQL Server stored procedures for beginners Debugging stored procedures in SQL Server Management Studio (SSMS) 210,336 Views

Follow us

Popular

SQL Convert Date functions and formats SQL Variables: Basics and usage SQL PARTITION BY Clause overview Different ways to SQL delete duplicate rows from a SQL Table How to UPDATE from a SELECT statement in SQL Server SQL Server functions for converting a String to a Date SELECT INTO TEMP TABLE statement in SQL Server SQL WHILE loop with simple examples How to backup and restore MySQL databases using the mysqldump command CASE statement in SQL Overview of SQL RANK functions Understanding the SQL MERGE statement INSERT INTO SELECT statement overview and examples SQL multiple joins for beginners with examples Understanding the SQL Decimal data type DELETE CASCADE and UPDATE CASCADE in SQL Server foreign key SQL Not Equal Operator introduction and examples SQL CROSS JOIN with examples The Table Variable in SQL Server SQL Server table hints – WITH (NOLOCK) best practices

Trending

SQL Server Transaction Log Backup, Truncate and Shrink Operations Six different methods to copy tables between databases in SQL Server How to implement error handling in SQL Server Working with the SQL Server command line (sqlcmd) Methods to avoid the SQL divide by zero error Query optimization techniques in SQL Server: tips and tricks How to create and configure a linked server in SQL Server Management Studio SQL replace: How to replace ASCII special characters in SQL Server How to identify slow running queries in SQL Server SQL varchar data type deep dive How to implement array-like functionality in SQL Server All about locking in SQL Server SQL Server stored procedures for beginners Database table partitioning in SQL Server How to drop temp tables in SQL Server How to determine free space and file size for SQL Server databases Using PowerShell to split a string into an array KILL SPID command in SQL Server How to install SQL Server Express edition SQL Union overview, usage and examples

Solutions

Read a SQL Server transaction logSQL Server database auditing techniquesHow to recover SQL Server data from accidental UPDATE and DELETE operationsHow to quickly search for SQL database data and objectsSynchronize SQL Server databases in different remote sourcesRecover SQL data from a dropped table without backupsHow to restore specific table(s) from a SQL Server database backupRecover deleted SQL data from transaction logsHow to recover SQL Server data from accidental updates without backupsAutomatically compare and synchronize SQL Server dataOpen LDF file and view LDF file contentQuickly convert SQL code to language-specific client codeHow to recover a single table from a SQL Server database backupRecover data lost due to a TRUNCATE operation without backupsHow to recover SQL Server data from accidental DELETE, TRUNCATE and DROP operationsReverting your SQL Server database back to a specific point in timeHow to create SSIS package documentationMigrate a SQL Server database to a newer version of SQL ServerHow to restore a SQL Server database backup to an older version of SQL Server

Categories and tips

►Auditing and compliance (50) Auditing (40) Data classification (1) Data masking (9) Azure (295) Azure Data Studio (46) Backup and restore (108) ►Business Intelligence (482) Analysis Services (SSAS) (47) Biml (10) Data Mining (14) Data Quality Services (4) Data Tools (SSDT) (13) Data Warehouse (16) Excel (20) General (39) Integration Services (SSIS) (125) Master Data Services (6) OLAP cube (15) PowerBI (95) Reporting Services (SSRS) (67) Data science (21) ►Database design (233) Clustering (16) Common Table Expressions (CTE) (11) Concurrency (1) Constraints (8) Data types (11) FILESTREAM (22) General database design (104) Partitioning (13) Relationships and dependencies (12) Temporal tables (12) Views (16) ▼Database development (418) Comparison (4) Continuous delivery (CD) (5) Continuous integration (CI) (11) Development (146) Functions (106) Hyper-V (1) Search (10) Source Control (15) SQL unit testing (23) Stored procedures (34) String Concatenation (2) Synonyms (1) Team Explorer (2) Testing (35) Visual Studio (14) DBAtools (35) DevOps (23) DevSecOps (2) Documentation (22) ETL (76) ►Features (213) Adaptive query processing (11) Bulk insert (16) Database mail (10) DBCC (7) Experimentation Assistant (DEA) (3) High Availability (36) Query store (10) Replication (40) Transaction log (59) Transparent Data Encryption (TDE) (21) Importing, exporting (51) Installation, setup and configuration (121) Jobs (42) ►Languages and coding (686) Cursors (9) DDL (9) DML (6) JSON (17) PowerShell (77) Python (37) R (16) SQL commands (196) SQLCMD (7) String functions (21) T-SQL (275) XML (15) Lists (12) Machine learning (37) Maintenance (99) Migration (50) Miscellaneous (1) ►Performance tuning (869) Alerting (8) Always On Availability Groups (82) Buffer Pool Extension (BPE) (9) Columnstore index (9) Deadlocks (16) Execution plans (125) In-Memory OLTP (22) Indexes (79) Latches (5) Locking (10) Monitoring (100) Performance (196) Performance counters (28) Performance Testing (9) Query analysis (121) Reports (20) SSAS monitoring (3) SSIS monitoring (10) SSRS monitoring (4) Wait types (11) ►Professional development (68) Professional development (27) Project management (9) SQL interview questions (32) Recovery (33) Security (84) Server management (24) SQL Azure (271) SQL Server Management Studio (SSMS) (90) SQL Server on Linux (21) ►SQL Server versions (177) SQL Server 2012 (6) SQL Server 2016 (63) SQL Server 2017 (49) SQL Server 2019 (57) SQL Server 2022 (2) ►Technologies (334) AWS (45) AWS RDS (56) Azure Cosmos DB (28) Containers (12) Docker (9) Graph database (13) Kerberos (2) Kubernetes (1) Linux (44) LocalDB (2) MySQL (49) Oracle (10) PolyBase (10) PostgreSQL (36) SharePoint (4) Ubuntu (13) Uncategorized (4) Utilities (21) Helpers and best practices BI performance counters SQL code smells rules SQL Server wait types © 2022 Quest Software Inc. ALL RIGHTS RESERVED. GDPR Terms of Use Privacy
Share:
0 comments

Comments (0)

Leave a Comment

Minimum 10 characters required

* All fields are required. Comments are moderated before appearing.

No comments yet. Be the first to comment!

Functions vs stored procedures in SQL Server | Trend Now | Trend Now