Sunteți pe pagina 1din 5

SQL Procedure

Syntax :- create procedure procedurename ( parameter list)

Begin

Statements;

End $$

Eg:- Create a procedure to display all tuple from employee table

Create Procedure my_proc_display() for single statement

Begin

Select * from employee; select * from employee; $$

End$$

Call my_proc_display() ; // to call procedure

Declaring variable in procedure

Syntax :- Declare variable_name Datatype Default value ;

Create procedure my_proc_add()

Begin

Declare x int Default 0;

Declare y int Default 0;

Declare z int Default 0;

Set x =20;

Set y=30;

Set z = x+y;

Select z;
End $$

Create procedure global()

Begin

Declare a int default 0;

Set @c = a+b;

End $$

Set @c=0;

Call global() $$

Select @c $$

Nested Begin

Create procedure my_proc_scope()

Begin

Declare a int default 50;

Declare b int default 100;

Select a,b;

Begin

Declare a int default 100;

Declare b int default 200;

Select a,b;

End$$

End $$
Types of Parameter

1) IN
2) OUT
3) INOUT

Create procedure parameter( IN input int)

Begin

Select * from employee

Where Salary > input;

End$$

Call parameter(10000) $$

Q.Create a procedure that return max salary of employee

Create procedure my_proc_parameterout ( OUT output int)

Begin

Select max(salary) into output from employee;

End $$

Call my_proc_parameterout(@output)

Select @output $$

Q. create a procedure that find max,min,avg & sum of salary from employee table

Depending on user input

Create procedure my_proc_func(IN input int, OUT output int)

Begin

If input=1 then

Select Max(salary) into output from employee;

Elseif input=2 then

Select min(salary) into output from employee;


Elseif input=3 then

Select avg(salary) into output from employee;

Elseif input=4 then

Select sum(salary)into output from employee;

Endif;

Call my_proc_func(2,@output) $$

Select @output $$

2. Case

When condition then

Statement

When(condt) then

Statement

Else

Statement

End case;

Loop Statement

Loop_label: LOOP

Statements;

Statements;

Terminating condt => if condt then

Set X = X+1 Leave loop_label

End loop End if;

Q. Create a procedure that display value from 1 to 10


Create procedure my_proc_cursor()

Begin

Declare name varchar(25);

Declare lastname varchar(25);

Declare Sal int;

Declare Flag int Default 0;

Declare cursor_test cursor for select Fname,Lastname,Salary from employee;

Declare continue handler

For not found set Flag =1;

Open cursor_test;

Loop_begin: loop

Fetch cursor_test into name,Lastname,Salary

Select name lastname salary ;

If flag =1 then

Leave loop_begin;

End if;

End loop;

End $$

S-ar putea să vă placă și