top of page
Learn T-SQL

Guide to SQL Server Stored Procedures

Updated: 4 days ago


Stored Procs In T-SQL By Mike Bennyhoff

Guide To SQL Server Stored Procedures In The Database

A SQL stored procedure is a set of SQL statements that are written once and then executed whenever needed. It's like a template that can be used over and over again, saving time and energy when performing common operations on a database. stored procedures are comprised of data manipulation language (DML) that allow the stored procedure to execute operations that may include retrieving data from database tables, logic to insert data, updating existing rows or delete data.



What Are Some Of The Key Features Of Stored Procedures In SQL Server:

Reusability: simple stored procedure can be called multiple times in an application, allowing for efficient reuse of code.


Performance: Stored procedures are precompiled, reducing the overhead of parsing and optimizing T-SQL statements. This can result in significant performance improvements when the stored procedure is called from multiple users


Input/Output parameters: stored procedure can accept input parameters and return multiple resultsets, making them flexible and useful in a variety of scenarios.


Error handling: Stored procedures can include error handling and exception management, making it easier to diagnose and resolve errors in the database layer.


Here's the basic syntax for creating a Transact-SQL stored procedure in SQL Server:

CREATE PROCEDURE [schema_name.]procedure_name
    (@parameter1 data_type [OUTPUT], 
     @parameter2 data_type, 
     ...)
AS
BEGIN
    -- T-SQL statements here
END

What Are The Types Of Stored Procedures In SQL Server


Stored Procedures Can Be Classified Into The Following Types:

System stored procedures:


In this guide to SQL Server Stored Procedures, we will discuss the stored procedures that are created and maintained by the SQL Server system, and are used to perform various administrative and maintenance tasks. Examples of system stored procedures include sp_help, sp_rename, and sp_who.


User-defined stored procedures:

These are stored procedures that are created and maintained by database administrators or developers, and are used to encapsulate business logic and perform specific tasks. User-defined stored procedures can be written in T-SQL or in .NET languages, such as C# or Visual Basic.


Extended stored procedures:

These are stored procedures that are implemented as dynamic link libraries (DLLs) and are executed directly by the SQL Server process. Extended stored procedures are typically used to perform low-level system tasks that cannot be performed using T-SQL.


CLR stored procedures:

These are stored procedures that are implemented in .NET languages and are executed by the .NET runtime. CLR stored procedures can perform complex operations and access the full range of .NET libraries and APIs, making them more powerful and flexible than T-SQL stored procedures.

Each type of stored procedure has its own advantages and disadvantages, and the choice of which type of stored procedure to use depends on the requirements of the application and the specific use case.


Stored Procedures vs Functions: What's the Difference?

For database administrators, stored procedures and functions are two of the most important tools at their disposal. But what exactly are these tools, and how do they differ from one another?


A stored procedure is a type of program that runs on a database server and can be used to execute commands or queries against data in a database. The main advantage of using stored procedures is that they allow you to store complex code within the database itself, making it easier to maintain and execute when needed. Additionally, since the code is executed on the server side, it can also be used for tasks such as transaction control, which can help improve performance when working with large datasets.


In contrast, functions are more lightweight than stored procedures. They are typically written in SQL statements and return a single value or set of values based on input parameters. One major benefit of functions is that they can be called directly from a query without having to execute an entire stored procedure each time. This makes them ideal for tasks such as formatting data or performing calculations on data within a query.


How to Create Stored Procedures In SQL Server Management Studio

To creat a new stored procedure in a SQL Server database open a query window then use the following syntax:

CREATE PROCEDURE procedure_name
(
   @parameter1 data_type,
   @parameter2 data_type,
   ...
)
AS
BEGIN
   -- statements
END

Replace "procedure_name" with the name you want to give to the stored procedure. Replace the parameters with your own names and data types, and replace the -- statements with the SQL code you want to execute.

For example, here is a simple stored procedure that returns the sum of two numbers:

The same syntax can be used to alter a stored procedure by using the alter procedure statement

CREATE PROCEDURE sum_of_two_numbers
(
   @num1 INT,
   @num2 INT
)
AS
BEGIN
   SELECT @num1 + @num2 AS result
END

Execute Stored Procedure SQL Server Management Studio. We can use ‘EXEC ProcedureName' to execute stored procedures.


Execute Stored Proc From SSMS

To Modify Stored procedures In SQL Server Management Studio you can right click or Use the system stored procedure sp_rename to rename an existing stored procedure.

View dependencies Of SQL Server Stored Procedures and and other objects created in DDL (Data Definition Language)

Modify Stored Procs From SSMS

If you need to find specific text here the following example is a great article on search for text in a stored proc


Who the author was


Schema Changes Report SSMS

View Extended Properties Of Stored ProcedureResources

Extended Props In SSMS

Using Parameters In A SQL Server Stored Procedure

In a stored procedure, parameters are used to pass values into the stored procedure. These values can be used in the SQL statements within the stored procedure to modify its behavior.


To use parameters in a stored procedure, you first need to declare them in the procedure header, using the @ symbol to indicate that they are parameters. For example:

CREATE PROCEDURE procedure_name
(
   @parameter1 data_type,
   @parameter2 data_type,
   ...
)
AS
BEGIN
   -- statements
END

Replace "procedure_name" with the name of your stored procedure, replace "parameter1" and "parameter2" with your own parameter names, and replace "data_type" with the data type of each parameter.


To use the parameters within the stored procedure, simply reference them in your SQL statements as if they were variables. For example:

CREATE PROCEDURE sum_of_two_numbers
(
   @num1 INT,
   @num2 INT
)
AS
BEGIN
   SELECT @num1 + @num2 AS result
END

In this example, the stored procedure accepts two parameters, @num1 and @num2, both of type INT. The stored procedure then calculates the sum of these two numbers and returns the result.


Why Do We Use SET NOCOUNT ON In A Stored Procedure?

SET NOCOUNT ON is a T-SQL statement used in stored procedures to prevent the display of the number of rows affected by a T-SQL statement. By default, SQL Server returns a message indicating the number of rows affected by each T-SQL statement executed by a stored procedure. This information can be useful for some applications, but it can also slow down the performance of the stored procedure, especially for stored procedures that execute a large number of statements.

The following is an example of how SET NOCOUNT ON can be used in a stored procedure:

CREATE PROCEDURE MyProcedure
AS
BEGIN
    SET NOCOUNT ON;
    -- T-SQL statements here
END


Using Try Catch Blocks For Error Handling

A TRY...CATCH block in T-SQL is used to handle exceptions, or errors, that occur during the execution of a Transact-SQL statement.

The basic syntax for using a TRY...CATCH block is as follows:

BEGIN TRY
   -- T-SQL statements that might raise an error
END TRY
BEGIN CATCH
   -- T-SQL statements to handle the error
END CATCH

The TRY block contains the T-SQL statements that you want to execute and that might raise an error. The CATCH block contains the T-SQL statements that will be executed in the event that an error occurs.


For example, the following code demonstrates how to use a TRY...CATCH block to handle a divide-by-zero error:

BEGIN TRY
   DECLARE @x INT = 5
   DECLARE @y INT = 0
   DECLARE @result INT

   SET @result = @x / @y
END TRY
BEGIN CATCH
   PRINT 'Error: divide by zero encountered.'
END CATCH

In this example, the TRY block attempts to divide @x by @y, which will raise a divide-by-zero error. The CATCH block then prints a message indicating that the error occurred.

You can also use the ERROR_NUMBER() and ERROR_MESSAGE() functions to obtain information about the error that occurred within the CATCH block. For example:

BEGIN TRY
   DECLARE @x INT = 5
   DECLARE @y INT = 0
   DECLARE @result INT

   SET @result = @x / @y
END TRY
BEGIN CATCH
   PRINT 'Error number: ' + CAST(ERROR_NUMBER() AS VARCHAR(10))
   PRINT 'Error message: ' + ERROR_MESSAGE()
END CATCH

This would print the error number and error message, allowing you to diagnose the problem and take appropriate action.


Other Resources


Related

250 views0 comments
bottom of page