Introduction
In this blog, I will explain the SQL Store Procedure. A stored procedure is a group of SQL statements that have been previously created and stored in the server database. It creates SQL queries to be stored and executed on the server. Parameters can also be passed to a stored procedure so that the stored procedure can act based on the parameter value(s) passed. Stored procedures accept input parameters so that a single procedure can be used over the network by several clients using different input data. One advantage of this procedure is that it helps reduce network traffic and improve performance.
Syntax
- CREATE PROCEDURE MASTER_PROC
- AS
- BEGIN
- SELECT * FROM EMPLOYEE
- END
- EXEC MASTER_PROC
Create a Store Procedure
1. The “CREATE PROCEDURE” statement is used to create a new stored procedure in a database.
2. Declare the Parameters and data types.
3. I have used the IF-ELSE Condition to perform all operations in a single Stored Procedure (SP).
4. “EXEC” keyword is used to execute the stored procedure
Coding
- CREATE PROCEDURE MASTER_PROC (@ID INT,@FIRST_NAME NVARCHAR(100),@LAST_NAME NVARCHAR(100),@DATE NVARCHAR(100),@TRANSACTTYPE VARCHAR(1))
- AS
- BEGIN
- IF(@TRANSACTTYPE='I')
- BEGIN
- INSERT INTO MASTER_TABLE(FIRST_NAME,LAST_NAME,DATE) VALUES(@FIRST_NAME,@LAST_NAME,@DATE)
- END
- ELSE IF(@TRANSACTTYPE='U')
- BEGIN
- UPDATE MASTER_TABLE SET FIRST_NAME=@FIRST_NAME,LAST_NAME=@LAST_NAME,DATE=@DATE WHERE ID=@ID
- END
- ELSE IF(@TRANSACTTYPE='D')
- BEGIN
- DELETE FROM MASTER_TABLE WHERE ID=@ID
- END
- END
Advantages:
1. Stored procedures are used so multiple queries execute a single execution.
2. They allow faster execution.
3. Help reduce network traffic
4. Stored procedures can be used for input and output parameters.