メインコンテンツへスキップ
SQL

User Defined Stored Procedures in SQL

Learn how to use and apply the user-defined stored procedure along with examining different types of stored procedures in SQL.
Olivia Smith
· 5 分 読む

AIで探求

ChatGPTClaudePerplexity

無料アカウントを作成する

練習とトラックであなたの進捗を記録しましょう。

Googleで登録
続行すると、弊社の利用規約、プライバシーポリシーに同意し、データが米国に保存されることに同意したことになります。

You will be using Microsoft SQL server as the database. The concept covered in this tutorial is the same for most of the Relational Database Management System's, but syntaxes are different, although the idea used here serves well for all databases.

Stored Procedure is the block of the SQL statement in Relational Database Management System (RDBMS), and it is typically written by the programmer, Database Administrator, Data Analyst, and is saved and re-used for multiple programs. It can also have different types depending on the various RDBMS. However, the two most crucial Stored Procedures found in any RDBMS are as follows.

  • User-defined Stored Procedure
  • System Stored Procedure

Stored Procedure is a prepared compiled code which is stored or cached and then re-used. You can have cached code for re-use which makes maintainability far easier, i.e., it doesn't need to be changed multiple times, which can maintain security.

Creating a Table

You will now create a table named table_Employees as follows.

CREATE TABLE table_Employees
(
    EmployeeId INT PRIMARY KEY NOT NULL,
    EmployeeFirstName VARCHAR(25) NOT NULL,
    EmployeeLastName VARCHAR(25) NOT NULL,
    EmployeeGender VARCHAR(25) NOT NULL,
    EmployeeDepartmentID INT

)

The table consists of information about employees in a particular company and consists of the following columns:

  1. EmployeeId: It is the primary key which is unique and is integer datatype, where the value gets auto-incremented.
  2. EmployeeFirstName: It is the First Name of an employee, which is of character data type and should not be left empty.
  3. EmployeeLast Name: It is the Last Name of an employee, which is of character data type and should not be left empty.
  4. EmployeeGender: It shows the Gender of the employee and is also a character type.
  5. EmployeeDepartmentId: It is the id of the employee of the integer data type.

You can write a query to insert values into the table. The queries to add values to the table is:

    INSERT INTO <TABLE_NAME>(<COLUMNS_OF_TABLE>) VALUES(<CORRESPONDING_VALUES_TO_MATCH_COLUMN>)

After inserting the values into the table, table_Employees is created.

table_Employees

To Create a User Defined Stored Procedure

Stored Procedure let's you write a query once, and the query has a name which can be saved and executed multiple times if needed. By executing the queries, you can have a folder created as Programmabilty->Stored Procedure, and there is the file named dbo.uprocGetEmployees.

The syntax for creating a Stored Procedure is:

CREATE PROCEDURE <<<procedure_name>>>
AS
BEGIN

   '''Required SQL Queries'''

END

You can create a Stored Procedure by using the SQL statement as follows.

  • CREATE PROCEDURE procedure_name
  • CREATE PROC procedure_name

Also, you need to create a Stored Procedure with a naming convention other than "sp_.". The Stored Procedure in the example is created with the name: uprocGetEmployees.

Stored Procedure example

To Execute the Stored Procedure

To execute a Stored procedure, you can use one of three approaches, and run it as follows.

  • EXEC <>
  • EXECUTE <>
  • <>

In the above program, you can use procedure name uprocGetEmployees and select it to execute the query.

Stored Procedure with Parameters

The Stored Procedure can accept single and multiple parameters. You can easily understand single parameters if you first understand multiple parameters.

The syntax for creating a Stored Procedure with multiple parameters is:

CREATE PROCEDURE <<procedure_name>> <<procedure_parameter>>
AS
    BEGIN
            <<sql_query>>
    END

The example shows that there is a change in the folder below.
EMPLOYEE->Programmability->Stored Procedures->dbo.uprocGetEmployessGenderAndDepartment

Stored Procedures with multiple parameters

The concept here is very similar to the function in general programming languages like Python, Java, etc. The program above has the function or procedure name called as "uprocGetEmployeesGenderAndDepartment", which has the parameter name @EmployeeGender and @EmployeeDepartmentId which are "called" by passing the required value to our procedure which can be done by one of two ways and it is explained below.

The parameters in this program are @EmployeeGender and @EmployeeDepartmentId which are "called" by passing the value to the parameter.

The value can be specified by one of two ways. You can use either one of them to execute the Stored Procedure with the multiple parameters.

  • By specifying the parameter names in the query and passing required values:

Specifying value 1

  • By the position that matches the parameter of Stored Procedure with your query and pass the required value to the parameter:

Specifying value 2

Modifying the Stored Procedure

You can also modify the Stored Procedure by using the ALTER PROCEDURE command.

    ALTER PROCEDURE uprocGetEmployeesGenderAndDepartment
@EmployeeGender nvarchar(25),
@EmployeeDepartmentId int
BEGIN
    SELECT EmployeeFirstName,EmployeeGender,EmployeeDepartmentId FROM table_Employees WHERE
    EmployeeGender = @EmployeeGender AND EmployeeDepartmentId = @EmployeeDepartmentId
END

Deleting Stored Procedure

Stored Procedures can be quickly deleted by using the following commands:

DROP PROC <> DROP PROCEDURE <>

Adding Security Through Encryption

The lock symbol indicated in the picture below to the left shows that Stored Procedure is encrypted which ensures only authorized people can access it.

encrypted Stored Procedure

Conclusion

You have just completed learning the basics of User Stored Procedures and the topics covered are conceptually similar to any RDBMS. You can learn more on DataCamp, by taking their Intermediate SQL Server course. Also, the following Stored Procedures tutorial will serve well in your learning.

トピック
SQL

SQL Courses

コース

SQL のデータ操作

4時間
338.5K
データサイエンスに関わる多様な問いに答え、PostgreSQL を使って、堅牢なデータセットを準備できるよう、複雑な SQL クエリ学びます。
詳しく見るコースを始める

コース

SQL Server 入門

4時間
173.9K
SQL Serverを使用して一般的なデータ操作タスクを実行する方法を学び、このデータベースシステムを用いた一般的なデータ操作タスクを習得しましょう。

無料アカウントを作成する

練習とトラックであなたの進捗を記録しましょう。

Googleで登録
続行すると、弊社の利用規約、プライバシーポリシーに同意し、データが米国に保存されることに同意したことになります。
もっと見る
関連

チュートリアル

SQL Stored Procedure: Automate and Optimize Queries

Learn the basics of SQL stored procedures and how to implement them in different databases, including MySQL and SQL Server.
Allan Ouko's photo

Allan Ouko

9 分

チュートリアル

Views (Virtual Tables) in SQL

In this tutorial, you will learn what views are, the different types available, and the pros and cons of using them.
Avinash Navlani's photo

Avinash Navlani

6 分

チュートリアル

SQL String Functions: A Beginner's Guide

Understand how to use SQL String Functions to clean and process text data efficiently.
Eugenia Anello's photo

Eugenia Anello

7 分

チュートリアル

Introduction to Indexing in SQL

In this tutorial, learn about indexing in databases and different types of indexing techniques.
Sayak Paul's photo

Sayak Paul

14 分

チュートリアル

Difference Between SQL and PL/SQL: When to Use Each

Understand the key differences between SQL and PL/SQL, their ideal use cases, and practical tips for choosing the right tool for efficient database development.
Allan Ouko's photo

Allan Ouko

7 分

チュートリアル

Introduction to the ALTER TABLE Statement in SQL

In this tutorial, you will learn how to use and apply the ALTER TABLE statement in SQL.
Sayak Paul's photo

Sayak Paul

7 分

もっと見る