Thursday, 9 August 2012

Stored procedures in sql:

A stored procedure (proc) is a group of PL/SQL statements that performs specific task.
• A procedure has two parts, header and body.
• The header consists of the name of the procedure and the parameters passed to the
procedure.
• The body consists of declaration section, execution section and exception section.
• A procedure may or may not return any value. A procedure may return more than one value
.

General Syntax to create a procedure:
CREATE [OR REPLACE] PROCEDURE proc_name [list of parameters]
IS
Declaration section
BEGIN
Execution section
EXCEPTION
Exception section
END;


Explanation:-
Create:It
will create a procedure.
Replace: It
will re‐create a procedure if it already exists.
We can pass parameters to the procedures in three ways.
1. IN‐parameters: ‐ These types of parameters are used to send values to stored procedures.
2. OUT‐parameters: ‐ These types of parameters are used to get values from stored
procedures. This is similar to a return type in functions but procedure can return values for
more than one parameters.
3. IN OUT‐parameters: ‐ This type of parameter allows us to pass values into a procedure and
get output values from the procedure.
IS indicates the beginning of the body of the procedure. The code between IS and BEGIN forms the
Declaration section.
Begin:It
contains the executable statement.
Exception: It
contains exception handling part. This section is optional.
End: It
will end the procedure.
The syntax within the brackets [ ] indicates that they are optional.
By using CREATE OR REPLACE together the procedure is created if it does not exist and if it exists
then it is replaced with the current code.


Syntax: EXECUTE [or EXEC] procedure_name (parameter);

Example:

CREATE PROCEDURE HelloWorld
AS
   DECLARE
   @mynvarchar NVARCHAR(50),
   @myfloat FLOAT

   SET @mynvarchar = @@VERSION
   SET @mynvarchar  = 'Hello, world!'
   SET @myfloat = 1.6180

   PRINT @mynvarchar
   RETURN (0)


No comments:

Post a Comment