The CREATE PROCEDURE keyword in SQL is used to define a stored procedure, which is a set of SQL statements that can be executed on demand. A stored procedure allows you to encapsulate logic and perform operations like data retrieval, updates, or other complex SQL queries in a reusable and efficient way.
Basic Syntax
CREATE PROCEDURE procedure_name
[parameter1 datatype [IN | OUT | INOUT],
parameter2 datatype [IN | OUT | INOUT],
...]
AS
BEGIN
-- SQL statements to be executed
END;
Explanation:
procedure_name: The name of the stored procedure.parameter1,parameter2, ...: These are optional input (IN), output (OUT), or input/output (INOUT) parameters that the procedure accepts. The parameter type can be any valid SQL datatype likeINT,VARCHAR,DATE, etc.BEGIN ... END: The block where the SQL statements are written.
Example of a simple stored procedure:
CREATE PROCEDURE GetEmployeeDetails (IN employee_id INT)
BEGIN
SELECT * FROM Employees
WHERE EmployeeID = employee_id;
END;
- This procedure, named
GetEmployeeDetails, accepts one input parameteremployee_idand retrieves the details of the employee with that ID from theEmployeestable.
Example of a stored procedure with multiple parameters:
CREATE PROCEDURE AddEmployee (IN first_name VARCHAR(100), IN last_name VARCHAR(100), IN hire_date DATE)
BEGIN
INSERT INTO Employees (FirstName, LastName, HireDate)
VALUES (first_name, last_name, hire_date);
END;
- This procedure inserts a new employee into the
Employeestable with theFirstName,LastName, andHireDatevalues provided as input parameters.
Calling a Stored Procedure:
To execute a stored procedure after it's created, you use the CALL statement:
CALL GetEmployeeDetails(123);
- This will call the
GetEmployeeDetailsprocedure and pass123as theemployee_idparameter.
Notes:
- The
INparameter is the default, meaning it is used to pass values into the procedure. - The
OUTparameter is used to pass values from the procedure back to the calling environment. - The
INOUTparameter is used to both pass a value into the procedure and receive a value back from the procedure. - The stored procedure can contain any valid SQL operations, including
SELECT,INSERT,UPDATE, andDELETE.
Different database systems (e.g., MySQL, SQL Server, PostgreSQL, etc.) may have variations in syntax, but the general concept is the same across most platforms.
No comments:
Post a Comment