SQL Procedures
SQL Procedures:
Procedures:
Procedures are like functions.
Procedures are easy to execute and save your time.
you do not have to write whole the sql statement again and again.
You only have to call the procedure.
You must create the table before you can apply procedure
on the table. Here I am applying procedures on doctor table
General syntax for procedures:
create procedure Procedure_Name
(
--Parameters
)
as
begin
--Your sql statements
End
Procedure for inserting records:
Create a procedure and specify number of Parameters that will be passed to procedure. Parameters are the columns of table in which you want to insert the record. Number of Parameters should be equal to number of columns of the table.
create procedure insertdoc
(
@Doctor_Id int, --Here goes your Parameters
@Doctor_name varchar(20),
@Fee int,
@Specialty varchar(20)
)
as
begin
insert into doctor values(@Doctor_Id,@Doctor_Name,@Fee,@Speciality)
end --Procedure ends here
To execute a procedure write following
exec insertdoc 110,'kalim',10,'dental'
Procedure for Deleting records:
To delete a record using procedure
Here delete procedure is accepting only one argument because records are deleted on the basis of primary key
create procedure deleterow
(
@Doctor_Id int,
)
as
begin
delete from doctor where doctor_id=@Doctor_Id
end
To execute the deleterow
Pass one argument which is primary key for a record As I am passing 109 Now execute procedure
exec deleterow 109
Procedure for Searching records:
Records can be searched by many conditions here I am searching on the basis of Doctor_id which is primary key.
create procedure searchrec
(
@Doctor_id int
)
As
begin
select * from doctor where doctor_id=@Doctor_id
end
exec searchrec 109
Procedure for Updating records:
create procedure updaterec
(
@Doctor_Name varchar(20),
@Fee int,
@Specialty varchar(20),
@Doctor_Id int
)
as
begin
update doctor set
Doctor_Name=@Doctor_Name,
Fee=@Fee,
Specialty=@Specialty
where doctor_id=@Doctor_id
end
--Now execute the procedure
exec updaterec1 'Kally',15000,'dentist',110
Comments
Post a Comment