Stored Procedure is set of sql statement or pl/sql programming also.which is perform a specific task. when we compile the stored procedure then one object of the stored procedure will be created in the database.There is no need to compile stored procedure again and again.There are some differences between stored procedure and function .
Create a simple procedure:
create procedure prcselect
as
select *from student
Execute procedure : There are some ways to execute the stored procedure:
Example:
First create a student table in your database and insert some values also as given below.
see it:
Create a stored procedure and Execute it
span style="font-family: Georgia, Times New Roman, serif;">
Now write the following code and execute it which is given below:
Note: In this above example stored procedure is returning only integer value.
execute prcselect
or
exec prcselect
or
prcselect
we can make stored procedure as option by specify the default value at the time of declaration.Example:
First create a student table in your database and insert some values also as given below.
see it:
Create a stored procedure and Execute it
create procedure prcselect(@id int=0)
as
begin
if @id <>0
begin
select*from student where sid=@id
end
else
select*from student
end
Calling the stored procedure:span style="font-family: Georgia, Times New Roman, serif;">
execute prcselect
execute prcselect
see output:- we can make stored procedure as optional by specify the default value at the time of declaration:
Example:
In this example i have altered previous stored procedure.After alter this again execute for create a new object .
alter procedure prcselect(@id int)
as
begin
declare @a int
select @a=age from student where sid=@id
return @a
end
declare @age int
exec @age=prcselect 104
print @age
output: Note: In this above example stored procedure is returning only integer value.
- Use of Out parameter in stored procedure:
alter procedure prcselect(@id int,@name varchar(30)out,@sage int out)
as
begin
select @name=name,@sage=age from student where sid=@id
end
calling the Stored procedure:see it:
declare @sage int
declare @name varchar (30)
exec prcselect 106,@name out,@sage out
print 'name is ' +@name+' age is '+cast(@sage as varchar(3))
Output:
Note:-Cast and convert are two function which can be used to convert a particular type of value into another type.
Benefits of stored procedure:
There are some benefits of stored procedure.which is give below:
- No need to recompile the code again and again.
- It is also more helpful for security purpose.
- Reduce the Sql injection problem.
- It is faster than function.
I hope this is helpful for you.
To Get the Latest Free Updates Subscribe
Click below to download all codes.
Download
0 comments:
Post a Comment