- SQL - Discussion
- SQL - Useful Resources
- SQL - Useful Functions
- SQL - Quick Guide
- SQL - Questions and Answers
- SQL - Datatype Functions
- SQL - Conversion Functions
- SQL - JSON Functions
- SQL - Cursor Functions
- SQL - Logical Functions
- SQL - Statistical Functions
- SQL - Text & Image Functions
- SQL - Numeric Functions
- SQL - Aggregate Functions
- SQL - String Functions
- SQL - Date Functions
- SQL - Database Tuning
- SQL - IN vs EXISTS
- SQL - Group By vs Order By
- SQL - Common Table Expression
- SQL - Cursors
- SQL - Date & Time
- SQL - Auto Increment
- SQL - Using Sequences
- SQL - Handling Duplicates
- SQL - Sub Queries
- SQL - Transactions
- SQL - NULL Values
- SQL - Stored Procedures
- SQL - Default Constraint
- SQL - Check Constraint
- SQL - Null Functions
- SQL - Min & Max
- SQL - Hosting
- SQL - Injection
- SQL - Comments
- SQL - Wildcards
- SQL - Non-Clustered Index
- SQL - Clustered Index
- SQL - Unique Index
- SQL - Primary Key
- - 工会诉Join
- SQL - Inner Join
- SQL - Using Joins
- SQL - Aliases
- SQL - EXCEPT Operator
- SQL - INTERSECT Operator
- SQL - UNION vs UNION ALL
- SQL - UNION Operator
- SQL - BETWEEN Operator
- SQL - NOT NULL
- SQL - IS NOT NULL
- SQL - IS NULL
- SQL - NOT EQUAL
- SQL - NOT Operator
- SQL - CASE
- SQL - EXISTS Operator
- SQL - ANY, ALL Operators
- SQL - IN Operator
- SQL - LIKE Operator
- SQL - BOOLEAN (BIT) Operator
- SQL - AND & OR
- SQL - Having Clause
- SQL - Group By Clause
- SQL - Order By Clause
- SQL - Distinct Clause
- SQL - Top Clause
- SQL - Where Clause
- SQL - Rename Views
- SQL - Drop Views
- SQL - Update Views
- SQL - Create Views
- SQL - Sorting Results
- SQL - Delete Query
- SQL - Update Query
- SQL - Insert Into Select
- SQL - Select Into
- SQL - Select Query
- SQL - Insert Query
- SQL - Constraints
- SQL - Delete Table
- SQL - Drop Table
- SQL - Alter Tables
- SQL - Temporary Tables
- SQL - Clone Tables
- SQL - Truncate Table
- SQL - Rename Table
- SQL - Show Tables
- SQL - Create Table
- SQL - Backup Database
- SQL - Show Database
- SQL - Rename Database
- SQL - Select Database
- SQL - Drop Database
- SQL - Create Database
- SQL - Expressions
- SQL - Operators
- SQL - Data Types
- SQL - Syntax
- SQL - Databases
- SQL - RDBMS Concepts
- SQL - Overview
- SQL - Home
5. 图瓦卢
- 页: 1
- 页: 1
- 结构-创建指数
- 页: 1
- 页: 1
- 页: 1
- SQL - Foreign Key
- 文 件
- ∗ E/CN.6/2009/1。
- 页: 1
- 页: 1
- 文 件
- 页: 1
- 页: 1
- 文 件
- 页: 1
Selected Reading
- Who is Who
- Computer Glossary
- HR Interview Questions
- Effective Resume Writing
- Questions and Answers
- UPSC IAS Exams Notes
SQL - Stored Procedures
A stored procedure is a group of pre-compiled SQL statements (prepared SQL code) that can be reused again and again.
They can be used to perform a wide range of database operations such as inserting, updating, or deleting data, generating reports, and performing complex calculations. Stored procedures are very useful because they allow you to encapsulate (bundle) a set of SQL statements as a single unit and execute them repeatedly with different parameters, making it easy to manage and reuse code.
Procedures have similar structure as functions; they accept parameters and perform operations when we call them; but the difference between them is that SQL stored procedures are simpler to write or create, whereas functions have a more rigid structure and support fewer clauses and functionapty.
Syntax
The basic syntax to create a stored procedure in SQL is as follows −
CREATE PROCEDURE procedure_name @parameter1 datatype, @parameter2 datatype AS BEGIN -- SQL statements to be executed END
Where,
The CREATE PROCEDURE statement is used to create the procedure. After creating the procedure, we can define any input parameters that the procedure may require. These parameters are preceded by the @ symbol and followed by their respective data types.
The AS keyword is used to begin the procedure definition. The SQL statements that make up the procedure are placed between the BEGIN and END keywords.
Creating a Procedure
We can create a stored procedure using the CREATE PROCEDURE statement in SQL. Following are the simple steps for creating a stored procedure −
Choose a name for the procedure.
Write the SQL code for the procedure, including to create the procedure in SQL Server.
We can then test the stored procedure by executing it with different input parameters.
Example
To understand it better let us consider the CUSTOMERS table which contains the personal details of customers including their name, age, address and salary etc. as shown below −
CREATE TABLE CUSTOMERS ( ID INT NOT NULL, NAME VARCHAR (20) NOT NULL, AGE INT NOT NULL, ADDRESS CHAR (25), SALARY DECIMAL (18, 2), PRIMARY KEY (ID) );
Now insert values into this table using the INSERT statement as follows −
INSERT INTO CUSTOMERS (ID,NAME,AGE,ADDRESS,SALARY) VALUES (1, Ramesh , 32, Ahmedabad , 2000.00 ); INSERT INTO CUSTOMERS (ID,NAME,AGE,ADDRESS,SALARY) VALUES (2, Khilan , 25, Delhi , 1500.00 ); INSERT INTO CUSTOMERS (ID,NAME,AGE,ADDRESS,SALARY) VALUES (3, kaushik , 23, Kota , 2000.00 ); INSERT INTO CUSTOMERS (ID,NAME,AGE,ADDRESS,SALARY) VALUES (4, Chaitap , 25, Mumbai , 6500.00 ); INSERT INTO CUSTOMERS (ID,NAME,AGE,ADDRESS,SALARY) VALUES (5, Hardik , 27, Bhopal , 8500.00 ); INSERT INTO CUSTOMERS (ID,NAME,AGE,ADDRESS,SALARY) VALUES (6, Komal , 22, MP , 4500.00 ); INSERT INTO CUSTOMERS (ID,NAME,AGE,ADDRESS,SALARY) VALUES (7, Muffy , 24, Indore , 10000.00 );
The table will be created as −
+----+----------+-----+-----------+----------+ | ID | NAME | AGE | ADDRESS | SALARY | +----+----------+-----+-----------+----------+ | 1 | Ramesh | 32 | Ahmedabad | 2000.00 | | 2 | Khilan | 25 | Delhi | 1500.00 | | 3 | kaushik | 23 | Kota | 2000.00 | | 4 | Chaitap | 25 | Mumbai | 6500.00 | | 5 | Hardik | 27 | Bhopal | 8500.00 | | 6 | Komal | 22 | MP | 4500.00 | | 7 | Muffy | 24 | Indore | 10000.00 | +----+----------+-----+-----------+----------+
Now, let s look at a simple example of creating a stored procedure that takes an input parameter and returns a result set.
In the following query, we are trying to first create the stored procedure with the name ‘GetCustomerInfo’. We then provide it with a single input parameter called @CutomerAge. The stored procedure then selects all records from the ‘CUSTOMERS’ table where the CutomerAge matches the input parameter.
CREATE PROCEDURE GetCustomerInfo @CutomerAge INT AS BEGIN SELECT * FROM CUSTOMERS WHERE AGE = @CutomerAge END
Output
This would produce the following result −
Commands completed successfully.
Verification
To verify the changes, once we have created the stored procedure, we can test it by executing it with different input parameters as shown in the query below −
EXEC GetCustomerInfo @CutomerAge = 25
This will return all columns from the CUSTOMERS table where the cutomer’s age is 25.
+----+----------+-----+-----------+----------+ | ID | NAME | AGE | ADDRESS | SALARY | +----+----------+-----+-----------+----------+ | 2 | Khilan | 25 | Delhi | 1500.00 | | 4 | Chaitap | 25 | Mumbai | 6500.00 | +----+----------+-----+-----------+----------+
Stored Procedure Parameter Types
Stored procedures in a database system can have different types of parameters, which are placeholders for values that will be passed to the stored procedure when it is executed. Following are the different types of stored procedure parameters in SQL −
S.No. | Parameter & Description |
---|---|
1 | Input parameters These parameters are used to pass values from the calpng program or user to the stored procedure. |
2 | Output parameters These parameters are used to return values from the stored procedure to the calpng program or user. |
3 | Input/Output parameters These parameters allow a stored procedure to accept input values and return output values. |
4 | Table-valued parameters These parameters are used to pass a table variable as a parameter to a stored procedure. |
5 | Default parameters These parameters are used to specify a default value that will be used if no value is passed for the parameter. |
6 | Cursor parameters These parameters are used to pass a cursor to a stored procedure. |
7 | Output XML parameters These parameters are used to return XML data from a stored procedure. |
Now, let us take a look at some of the most common types of stored procedure parameters in SQL −
Procedure with IN parameter
The IN parameter is the default parameter that will receive input value from the program.
We can pass the values as arguments when the stored procedure is being executed. These values are read-only, which means they cannot be modified by the stored procedure.
Example
In the following query we are trying to create a stored procedure that takes a customer’s ID as an input parameter and returns that customer’s salary.
The procedure body simply performs a SELECT statement to retrieve the "Salary" column from the "CUSTOMERS" table, where the "CustomerID" matches the input parameter.
CREATE PROCEDURE GetCustomerSalary @CustomerID INT AS BEGIN SELECT SALARY FROM CUSTOMERS WHERE ID = @CustomerID END
Output
This would produce the following result −
Commands completed successfully.
Verification
To execute the stored procedure and pass in a value for the "@CustomerID" parameter, we will use the EXEC command as given below −
EXEC GetCustomerSalary @CustomerID = 6
This will return the salary for the customer with an ID of 6, assuming there is a corresponding row in the "Customers" table −
+----------+ | SALARY | +----------+ | 4500.00 | +----------+
Procedure with OUT parameter
The OUT parameter sends output value to the program. It allows us to return a value or set of values to the calpng program.
Note that when using an OUT parameter, we must specify the keyword "OUT" after the parameter name when passing it to the stored procedure. This tells SQL Server that the parameter is an output parameter and should be assigned a value by the stored procedure.
Example
In the following query we are trying to create a stored procedure that takes the customer’s ID as an input parameter and returns that customer’s salary using an output parameter "@Salary" which holds the salary value returned by the stored procedure.
The procedure body performs a SELECT statement to get the "Salary" column from the "CUSTOMERS" table, where the "ID" matches the input parameter. We use the the assignment operator "=" to assign the returned value to our output parameter "@Salary".
CREATE PROCEDURE GetCustomerSalary @CustomerID INT, @Salary DECIMAL(18,2) OUT AS BEGIN SELECT @Salary = SALARY FROM CUSTOMERS WHERE ID = @CustomerID END
Output
This would produce the following result −
Commands completed successfully.
Verification
Here, we first declare a variable "@CustSalary" of the same datatype as the output parameter "@Salary". We then execute the stored procedure using the EXEC command, passing in the "@CustomerID " parameter and the "@Salary" parameter as an output parameter. Finally, we SELECT the value of the "@CustSalary" variable to display the customer’s salary in the result set.
DECLARE @CustSalary DECIMAL(18, 2) EXEC GetCustomerSalary @CustomerID = 4, @Salary = @CustSalary OUT SELECT @CustSalary AS Customer Salary
This will return the output as shown below −
+-------------------+ | Customer Salary | +-------------------+ | 6500.00 | +-------------------+
Procedure with INOUT parameter
The INOUT parameter is a combination of an IN parameter and an OUT parameter, and it allows us to both pass data into the stored procedure and receive data from the stored procedure.
To declare an INOUT parameter in a stored procedure, we need to use the OUTPUT keyword before the parameter name.
Example
In the following query, we provide two INOUT parameters to the stored procedure: cust_id and salary. The @salary parameter is specified as an OUTPUT parameter, which allows it to be used as both an input and an output parameter.
The stored procedure first retrieves the current salary of the customer from the database using the cust_id parameter. It then increases the salary by 10% and updates the customer’s salary in the database using the cust_id parameter.
CREATE PROCEDURE increaseSalary @cust_id INT, @salary DECIMAL(18, 2) OUTPUT AS BEGIN -- get the current salary of the customer SELECT @salary = SALARY FROM CUSTOMERS WHERE ID = @cust_id; -- increase the salary by 10% SET @salary = @salary * 1.1; -- update the cutomer s salary in the database UPDATE CUSTOMERS SET SALARY = @salary WHERE ID = @cust_id; END;
Output
This would produce the following result −
Commands completed successfully.
Verification
Here we declare and initiapze the @cust_id and @salary variables with the values of the Customer ID and salary we want to update. We then call the ‘increaseSalary’ stored procedure, passing in the variables as parameters. The @salary parameter is specified as an OUTPUT parameter, which allows it to be updated within the stored procedure. Finally, we retrieve the updated value of the @salary variable using a SELECT statement.
DECLARE @cust_id INT; DECLARE @salary DECIMAL(18, 2); SET @cust_id = 7; SET @salary = 50000.00; EXEC increaseSalary @cust_id, @salary OUTPUT; SELECT @salary AS Customer Salary
This will return the output as shown below −
+-------------------+ | Customer Salary | +-------------------+ | 11000.00 | +-------------------+
How To Rename a Stored Procedure
To rename a stored procedure in SQL, we use the built-in system stored procedure called sp_rename.
Syntax
Following is the basic syntax to rename a stored procedure in SQL −
sp_rename old_procedure_name , new_procedure_name ;
Example
In the following query we are trying to rename the existing stored procedure ‘GetCustomerSalary’ to ‘newProcedure’−
sp_rename GetCustomerSalary , newProcedure ;
Output
After executing the above query, the GetCustomerSalary stored procedure will be renamed to ‘newProcedure’.
Caution: Changing any part of an object name could break scripts and stored procedures.
Note − Note that if the stored procedure is referenced by other objects such as views or other stored procedures, we need to update those references manually to reflect the new name of the stored procedure. Additionally, renaming a stored procedure may impact any scripts or apppcations that rely on the old name, so it s a good idea to test our changes thoroughly before deploying them to production.
How To Modify a Stored Procedure
To modify an existing stored procedure in SQL, we use the ALTER PROCEDURE statement. We can add or remove parameters using ALTER PROCEDURE statement.
Note that when we modify a stored procedure, any dependent objects or code that references to it will also need to be modified accordingly.
Syntax
Following is the basic syntax to modify a stored procedure in SQL −
ALTER PROCEDURE procedure_name AS BEGIN -- New procedure code goes here END
Example
Let s say we have a stored procedure called ‘GetCustomerSalary’ that takes in one parameter called @Customer_ID and returns the details of the customer with that ID as shown below −
-- Original stored procedure CREATE PROCEDURE GetCustomerSalary @CustomerID INT AS BEGIN SELECT * FROM CUSTOMERS WHERE ID = @CustomerID END
Following is the output of the above query −
Commands completed successfully.
Now, we are trying to modify the ‘GetCustomerSalary’ stored procedure by adding a new parameter called @CustomerName of type VARCHAR(20). We then modify the SELECT statement to filter on both ‘ID’ and ‘NAME’.
ALTER PROCEDURE GetCustomerSalary @CustomerID INT, @CustomerName VARCHAR(20) AS BEGIN SELECT * FROM CUSTOMERS WHERE ID = @CustomerID AND NAME = @CustomerName END
Output
The result produced is as follows −
Commands completed successfully.How To Delete a Stored Procedure
To delete a stored procedure in SQL, we use the DROP PROCEDURE statement.
Note that dropping a stored procedure will permanently delete it, so make sure that we really want to delete it before executing the DROP PROCEDURE statement. Additionally, dropping a stored procedure may impact any scripts or apppcations that rely on the stored procedure, so it s a good idea to test our changes thoroughly before deploying them to production.
Syntax
Following is the basic syntax to delete a stored procedure in SQL −
DROP PROCEDURE [IF EXISTS] procedure_name;
Example
DROP PROCEDURE IF EXISTS GetCustomerSalary;
Output
The result produced is as follows −
Commands completed successfully.
Advantages of Stored Procedure
Following are the advantages of stored procedures −
Improved Performance − Stored procedures are pre-compiled and stored on the server, so they can be executed more quickly than SQL statements that are sent from cpent apppcations.
Code Reuse − Stored procedures can be called from different cpent apppcations, which means that the same code can be reused across different apppcations. This reduces development time and maintenance costs.
Reduced Network Traffic − Because stored procedures are executed on the server, only the results are returned to the cpent, which reduces network traffic and improves apppcation performance.
Better Security − Stored procedures can be used to enforce security rules and prevent unauthorized access to sensitive data. They can also pmit the actions that can be performed by users, making it easier to maintain data integrity and consistency.
Simppfied Maintenance − By storing SQL code in a single location, it becomes easier to maintain and update the code. This makes it easier to fix bugs, add new functionapty, and optimize performance.
Drawbacks of Stored Procedure
Following are the disadvantages of stored procedures −
Increased Overhead − Stored procedures can consume more server resources than simple SQL statements, particularly when they are used frequently or for complex operations.
Limited Portabipty − Stored procedures are often specific to a particular database management system (DBMS), which means they may not be easily portable to other DBMSs.
Debugging Challenges − Debugging stored procedures can be more challenging than debugging simple SQL statements, particularly when there are multiple layers of code involved.
Security Risks − If stored procedures are not written correctly, they can pose a security risk, particularly if they are used to access sensitive data or to perform actions that could compromise the integrity of the database.