Procedures
Procedures
Function
Function, in computer programming language context,
a set of instructions which takes some input and
performs certain tasks. In SQL, a function returns a
value.
Procedure
Procedure, as well, is a set of instructions which takes
input and performs certain task. In SQL, procedure
does not return a value. In java, procedure and
functions are same and also called sub-routines.
Following are the important differences between SQL
Function and SQL Procedure.
A stored procedure is a prepared SQL code
that you can save, so the code can be
reused over and over again.
So if you have an SQL query that you write
over and over again, save it as a stored
procedure, and then just call it to execute
it.
You can also pass parameters to a stored
procedure, so that the stored procedure
can act based on the parameter value(s)
that is passes.
Stored Procedure Syntax
CREATE PROCEDURE procedure_name
AS
sql_statement
GO;
Execute a Stored
Procedure
EXEC procedure_name;
Stored Procedure With One Parameter
The following SQL statement creates a stored procedure
that selects Customers from a particular City from the
"Customers" table:
CREATE PROCEDURE SelectAllCustomers @City
nvarchar(30)
AS
SELECT * FROM Customers WHERE City = @City
GO;
Example
CREATE PROCEDURE SelectAllCustomers @City
nvarchar(30), @PostalCode nvarchar(10)
AS
SELECT * FROM Customers WHERE City =
@City AND PostalCode = @PostalCode
GO;
Execute the stored procedure above as follows:
Example
EXEC SelectAllCustomers @City = 'London',
@PostalCode = 'WA1 1DP';