Here is the first stored procedure source code:
1.CREATE PROCEDURE Delete_Employee
2. (@EmployeeId INT)
6. DELETE FROM Employees
7. WHERE EmployeeId = @EmployeeId;
A stored procedure must contains at least three parts: stored procedure name, parameter list and its body.
The CREATE PROCEDURE is similar to CREATE TABLE or INDEX statement. It is actually a SQL statement. The CREATE PROCEDURE will force the database server add the stored procedure to the its catalog. The name of stored procedure is followed after the CREATE PROCEDURE statement, in this case it is Delete_Employee. It would be the best that the name is meaningful and follows by the naming convention of the database server specification, for example each stored procedure should begin with "sp". In almost relation database product, the name of stored procedure must be unique.
The second part of the stored procedure is parameter list. In this case the list contains only one parameter @EmployeeId (the employee identity). Microsoft SQL Server requires prefix @ for every parameters and variables of stored procedure. Followed each parameter is its type, in this case, its type is integer (INT).
The main part of a stored procedure is the stored procedure body. It starts with keywords BEGIN and ends with keyword END. In this example the body is very simple; It deletes employee by employee identity.
When all syntax statements inside body are correct, the database server will store the stored procedure name and code in its catalog for reusing later by another stored procedure or programs.
Calling a stored procedure
We can call a stored procedure from the console window, from another stored procedure or from a program which can access database server. The syntax of calling a stored procedure is simple as follows:
The EXEC statement is used to invoke a stored procedure. After the EXEC statement is the stored procedure name followed by parameter list. This is an example to delete anemployees with identity is 8 by calling the sample procedure above Delete_Employee:
If a stored procedure has more than one parameters, the values of them can be passed to it and separated by a comma.
As you see writing and calling a stored procedure is very simple and easy. In the following tutorials, we will show you the feature and syntax of a stored procedure along with statement which can be used inside the body so you can empower its power. Next you will learn how to use parameter list to pass and get data in and out of stored procedures parameter list in stored procedure.