SlideShare una empresa de Scribd logo
1 de 14
Stored Procedure
By Deepak Sharma
Software Developer
What is Stored Procedure?
• A stored procedure is a group of sql
statements that has been created and stored
in the database.
• Stored procedure will accepts input
parameters so that a single procedure can be
used over network by several clients using
different input data.
Benefit of Stored Procedure
• Stored procedure will reduce network traffic
and increase the performance.
• If we modify stored procedure all clients will
get the updated stored procedure.
Types of Stored Procedure
1. System Stored Procedure
2. User Defined Stored Procedure
Types of User Defined Stored Procedure:-
1. Non Parameterized Stored Procedure
2. Parameterized Stored Procedure
--¤ USER DEFINED PROCEDURE-"NON
PARAMETERIZED STORED
PROCEDURE"
Firstly we have to create table:-
• create table contact(id int,name nvarchar(15),age int)
• select * from contact
• insert into contact select 1,'Deepak',23 union all select 2,'Shipra',23
union all select 3,'Richa',23 union all select 4,'Rashi',23
--¤ USER DEFINED PROCEDURE-"NON
PARAMETERIZED STORED
PROCEDURE"
Create Procedure:-
• create proc ProcDemo_select as select * from contact
Here proc declare as a procedure and you can also write procedure.
Fore execute this procedure :-
• exec ProcDemo_select
--¤ USER DEFINED PROCEDURE -
"PARAMETERIZED PROCEDURE"
• create proc ProcDemo_insert(@id int, @name nvarchar(15), @age int) as insert into
contact values(@id,@name,@age)
• exec ProcDemo_insert 4,'Aryan',23
• --or
• --ProcDemo_insert 5,'Hello',23
• exec ProcDemo_select
• -------------------------------------------------------------------------------------------------------------------
• create proc ProcDemo_update(@id int,@name nvarchar(15), @age int) as update
contact set name=@name, age=@age where id=@id
• exec ProcDemo_update 4,'Radha',23
• exec ProcDemo_select
• -------------------------------------------------------------------------------------------------------------------
• create proc ProcDemo_delete(@id int) as delete from contact where id=@id
• exec ProcDemo_delete 4
• exec ProcDemo_select
FOR VIEW ALL OF QUERY OF
STORED PROCEDURE
• sp_helptext ProcDemo_select
• sp_helptext ProcDemo_insert
• sp_helptext ProcDemo_update
• sp_helptext ProcDemo_delete
FOR DELETE STORED PROCEDURE
• drop proc ProcDemo_select
• drop proc ProcDemo_insert
• drop proc ProcDemo_update
• drop proc ProcDemo_delete
NAMING STRORED PROCEDURE
OBJECT
So some of these may be:
• uspInsertPerson - insert a new person record
• uspGetAccountBalance - get the balance of an account
• uspGetOrderHistory - return list of orders
STORED PROCEDURE USING TRY & CATCH BLOCK-:-
• CREATE PROCEDURE ProcDemo_TryCatch AS BEGIN TRY
SELECT * from contact
END TRY
BEGIN CATCH
SELECT ERROR_NUMBER() AS ErrorNumber, ERROR_SEVERITY() AS
ErrorSeverity, ERROR_STATE() AS ErrorState, ERROR_PROCEDURE() AS
ErrorProcedure, ERROR_LINE() AS ErrorLine, ERROR_MESSAGE() AS
ErrorMessage;
END CATCH
exec ProcDemo_TryCatch
FOR CALCULATING AVERAGE
• create proc ProcedureAverage as select AVG(id) as Average from contact
• exec ProcedureAverage
USING STORED PROCEDURE WITH ASP.NET
PAGE WITH TRANSACTION ON .ASPX PAGE-:-
create table test(id int,name varchar(20))
select * from test
insert test select 1,'Deepak' union all select 2,'Rashi'
create proc sp_Test(@id int,@name varchar(20)) as
begin try
insert into test values(@id,@name)
END TRY
BEGIN CATCH
SELECT
ERROR_LINE(),ERROR_NUMBER(),ERROR_PROCEDURE(),ERROR_SEVERITY(
),ERROR_STATE(),ERROR_MESSAGE();
END CATCH
drop proc sp_Test
allow a developer to work with transaction with two simple statement:
¤ Begin Transaction
¤ Commit Transaction
ADO.NET TRANSACTION:-
con.Open(); SqlTransaction trans; trans = con.BeginTransaction();
try
{
cmd = new SqlCommand("sp_Test", con);
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("@id", SqlDbType.Int).Value = txtID.Text;
cmd.Parameters.AddWithValue("@name", SqlDbType.VarChar).Value = txtName.Text.ToString();
cmd.Transaction = trans;
cmd.ExecuteNonQuery();
trans.Commit();
}
catch
{
trans.Rollback();
Label1.Text = "Insert Fail";
}
con.Close(); con.Dispose();
Thanks
By Deepak Sharma
Software Developer

Más contenido relacionado

La actualidad más candente

pl/sql Procedure
pl/sql Procedurepl/sql Procedure
pl/sql ProcedurePooja Dixit
 
MySql Triggers Tutorial - The Webs Academy
MySql Triggers Tutorial - The Webs AcademyMySql Triggers Tutorial - The Webs Academy
MySql Triggers Tutorial - The Webs Academythewebsacademy
 
Triggers in SQL | Edureka
Triggers in SQL | EdurekaTriggers in SQL | Edureka
Triggers in SQL | EdurekaEdureka!
 
Packages in PL/SQL
Packages in PL/SQLPackages in PL/SQL
Packages in PL/SQLPooja Dixit
 
Procedure and Functions in pl/sql
Procedure and Functions in pl/sqlProcedure and Functions in pl/sql
Procedure and Functions in pl/sqlÑirmal Tatiwal
 
SQL Queries Information
SQL Queries InformationSQL Queries Information
SQL Queries InformationNishant Munjal
 
Mysql Crud, Php Mysql, php, sql
Mysql Crud, Php Mysql, php, sqlMysql Crud, Php Mysql, php, sql
Mysql Crud, Php Mysql, php, sqlAimal Miakhel
 
Postgres vs Mongo / Олег Бартунов (Postgres Professional)
Postgres vs Mongo / Олег Бартунов (Postgres Professional)Postgres vs Mongo / Олег Бартунов (Postgres Professional)
Postgres vs Mongo / Олег Бартунов (Postgres Professional)Ontico
 
Nested Queries Lecture
Nested Queries LectureNested Queries Lecture
Nested Queries LectureFelipe Costa
 

La actualidad más candente (20)

pl/sql Procedure
pl/sql Procedurepl/sql Procedure
pl/sql Procedure
 
PL/SQL TRIGGERS
PL/SQL TRIGGERSPL/SQL TRIGGERS
PL/SQL TRIGGERS
 
trigger dbms
trigger dbmstrigger dbms
trigger dbms
 
Introduction to triggers
Introduction to triggersIntroduction to triggers
Introduction to triggers
 
MySql Triggers Tutorial - The Webs Academy
MySql Triggers Tutorial - The Webs AcademyMySql Triggers Tutorial - The Webs Academy
MySql Triggers Tutorial - The Webs Academy
 
Triggers in SQL | Edureka
Triggers in SQL | EdurekaTriggers in SQL | Edureka
Triggers in SQL | Edureka
 
Trigger in mysql
Trigger in mysqlTrigger in mysql
Trigger in mysql
 
Stored procedures
Stored proceduresStored procedures
Stored procedures
 
View & index in SQL
View & index in SQLView & index in SQL
View & index in SQL
 
Plsql
PlsqlPlsql
Plsql
 
Packages in PL/SQL
Packages in PL/SQLPackages in PL/SQL
Packages in PL/SQL
 
Oracle SQL Advanced
Oracle SQL AdvancedOracle SQL Advanced
Oracle SQL Advanced
 
Sql Functions And Procedures
Sql Functions And ProceduresSql Functions And Procedures
Sql Functions And Procedures
 
Procedure and Functions in pl/sql
Procedure and Functions in pl/sqlProcedure and Functions in pl/sql
Procedure and Functions in pl/sql
 
SQL Queries Information
SQL Queries InformationSQL Queries Information
SQL Queries Information
 
Mysql Crud, Php Mysql, php, sql
Mysql Crud, Php Mysql, php, sqlMysql Crud, Php Mysql, php, sql
Mysql Crud, Php Mysql, php, sql
 
Introduction to sql
Introduction to sqlIntroduction to sql
Introduction to sql
 
MySQL Views
MySQL ViewsMySQL Views
MySQL Views
 
Postgres vs Mongo / Олег Бартунов (Postgres Professional)
Postgres vs Mongo / Олег Бартунов (Postgres Professional)Postgres vs Mongo / Олег Бартунов (Postgres Professional)
Postgres vs Mongo / Олег Бартунов (Postgres Professional)
 
Nested Queries Lecture
Nested Queries LectureNested Queries Lecture
Nested Queries Lecture
 

Destacado (16)

cv deepak sharma
cv deepak sharmacv deepak sharma
cv deepak sharma
 
Intro to cao &store program
Intro to cao &store programIntro to cao &store program
Intro to cao &store program
 
MVC by asp.net development company in india
MVC by asp.net development company in indiaMVC by asp.net development company in india
MVC by asp.net development company in india
 
Triggers ppt
Triggers pptTriggers ppt
Triggers ppt
 
ADO.NET by ASP.NET Development Company in india
ADO.NET by ASP.NET  Development Company in indiaADO.NET by ASP.NET  Development Company in india
ADO.NET by ASP.NET Development Company in india
 
DB2-SQL Part-2
DB2-SQL Part-2DB2-SQL Part-2
DB2-SQL Part-2
 
Ajax Ppt 1
Ajax Ppt 1Ajax Ppt 1
Ajax Ppt 1
 
2.computer org.
2.computer org.2.computer org.
2.computer org.
 
Introduction to triggers
Introduction to triggersIntroduction to triggers
Introduction to triggers
 
Procedures and triggers in SQL
Procedures and triggers in SQLProcedures and triggers in SQL
Procedures and triggers in SQL
 
11 instruction sets addressing modes
11  instruction sets addressing modes 11  instruction sets addressing modes
11 instruction sets addressing modes
 
Addressing modes (detailed data path)
Addressing modes (detailed data path)Addressing modes (detailed data path)
Addressing modes (detailed data path)
 
Trigger
TriggerTrigger
Trigger
 
Addressing modes
Addressing modesAddressing modes
Addressing modes
 
Ajax ppt - 32 slides
Ajax ppt - 32 slidesAjax ppt - 32 slides
Ajax ppt - 32 slides
 
Introduction to Angularjs
Introduction to AngularjsIntroduction to Angularjs
Introduction to Angularjs
 

Similar a Stored procedure

Découvrir dtrace en ligne de commande.
Découvrir dtrace en ligne de commande.Découvrir dtrace en ligne de commande.
Découvrir dtrace en ligne de commande.CocoaHeads France
 
Building source code level profiler for C++.pdf
Building source code level profiler for C++.pdfBuilding source code level profiler for C++.pdf
Building source code level profiler for C++.pdfssuser28de9e
 
6 tips for improving ruby performance
6 tips for improving ruby performance6 tips for improving ruby performance
6 tips for improving ruby performanceEngine Yard
 
Денис Резник "Зачем мне знать SQL и Базы Данных, ведь у меня есть ORM?"
Денис Резник "Зачем мне знать SQL и Базы Данных, ведь у меня есть ORM?"Денис Резник "Зачем мне знать SQL и Базы Данных, ведь у меня есть ORM?"
Денис Резник "Зачем мне знать SQL и Базы Данных, ведь у меня есть ORM?"Fwdays
 
Scaling MySQL Strategies for Developers
Scaling MySQL Strategies for DevelopersScaling MySQL Strategies for Developers
Scaling MySQL Strategies for DevelopersJonathan Levin
 
Predix 따라하기 2
Predix 따라하기 2Predix 따라하기 2
Predix 따라하기 2HeeJung Park
 
SQL Server Deep Drive
SQL Server Deep Drive SQL Server Deep Drive
SQL Server Deep Drive DataArt
 
Labs_BT_20221017.pptx
Labs_BT_20221017.pptxLabs_BT_20221017.pptx
Labs_BT_20221017.pptxssuserb4d806
 
Writing efficient sql
Writing efficient sqlWriting efficient sql
Writing efficient sqlj9soto
 
2008 Collaborate IOUG Presentation
2008 Collaborate IOUG Presentation2008 Collaborate IOUG Presentation
2008 Collaborate IOUG PresentationBiju Thomas
 
MySQL Performance Schema in Action
MySQL Performance Schema in ActionMySQL Performance Schema in Action
MySQL Performance Schema in ActionSveta Smirnova
 
Oracle Database Performance Tuning Advanced Features and Best Practices for DBAs
Oracle Database Performance Tuning Advanced Features and Best Practices for DBAsOracle Database Performance Tuning Advanced Features and Best Practices for DBAs
Oracle Database Performance Tuning Advanced Features and Best Practices for DBAsZohar Elkayam
 
[2019.1] 하이퍼레저 패브릭 v1.3, v1.4 새로운 기능
[2019.1] 하이퍼레저 패브릭 v1.3, v1.4 새로운 기능[2019.1] 하이퍼레저 패브릭 v1.3, v1.4 새로운 기능
[2019.1] 하이퍼레저 패브릭 v1.3, v1.4 새로운 기능Hyperledger Korea User Group
 
Best Practices in Security with PostgreSQL
Best Practices in Security with PostgreSQLBest Practices in Security with PostgreSQL
Best Practices in Security with PostgreSQLEDB
 
Common schema my sql uc 2012
Common schema   my sql uc 2012Common schema   my sql uc 2012
Common schema my sql uc 2012Roland Bouman
 
Common schema my sql uc 2012
Common schema   my sql uc 2012Common schema   my sql uc 2012
Common schema my sql uc 2012Roland Bouman
 

Similar a Stored procedure (20)

Découvrir dtrace en ligne de commande.
Découvrir dtrace en ligne de commande.Découvrir dtrace en ligne de commande.
Découvrir dtrace en ligne de commande.
 
Building source code level profiler for C++.pdf
Building source code level profiler for C++.pdfBuilding source code level profiler for C++.pdf
Building source code level profiler for C++.pdf
 
6 tips for improving ruby performance
6 tips for improving ruby performance6 tips for improving ruby performance
6 tips for improving ruby performance
 
Денис Резник "Зачем мне знать SQL и Базы Данных, ведь у меня есть ORM?"
Денис Резник "Зачем мне знать SQL и Базы Данных, ведь у меня есть ORM?"Денис Резник "Зачем мне знать SQL и Базы Данных, ведь у меня есть ORM?"
Денис Резник "Зачем мне знать SQL и Базы Данных, ведь у меня есть ORM?"
 
Scaling MySQL Strategies for Developers
Scaling MySQL Strategies for DevelopersScaling MySQL Strategies for Developers
Scaling MySQL Strategies for Developers
 
Predix 따라하기 2
Predix 따라하기 2Predix 따라하기 2
Predix 따라하기 2
 
Hack through Injections
Hack through InjectionsHack through Injections
Hack through Injections
 
SQL Server Deep Drive
SQL Server Deep Drive SQL Server Deep Drive
SQL Server Deep Drive
 
Labs_BT_20221017.pptx
Labs_BT_20221017.pptxLabs_BT_20221017.pptx
Labs_BT_20221017.pptx
 
Writing efficient sql
Writing efficient sqlWriting efficient sql
Writing efficient sql
 
Rails Security
Rails SecurityRails Security
Rails Security
 
2008 Collaborate IOUG Presentation
2008 Collaborate IOUG Presentation2008 Collaborate IOUG Presentation
2008 Collaborate IOUG Presentation
 
MySQL Performance Schema in Action
MySQL Performance Schema in ActionMySQL Performance Schema in Action
MySQL Performance Schema in Action
 
Database training for developers
Database training for developersDatabase training for developers
Database training for developers
 
Stored procedure
Stored procedureStored procedure
Stored procedure
 
Oracle Database Performance Tuning Advanced Features and Best Practices for DBAs
Oracle Database Performance Tuning Advanced Features and Best Practices for DBAsOracle Database Performance Tuning Advanced Features and Best Practices for DBAs
Oracle Database Performance Tuning Advanced Features and Best Practices for DBAs
 
[2019.1] 하이퍼레저 패브릭 v1.3, v1.4 새로운 기능
[2019.1] 하이퍼레저 패브릭 v1.3, v1.4 새로운 기능[2019.1] 하이퍼레저 패브릭 v1.3, v1.4 새로운 기능
[2019.1] 하이퍼레저 패브릭 v1.3, v1.4 새로운 기능
 
Best Practices in Security with PostgreSQL
Best Practices in Security with PostgreSQLBest Practices in Security with PostgreSQL
Best Practices in Security with PostgreSQL
 
Common schema my sql uc 2012
Common schema   my sql uc 2012Common schema   my sql uc 2012
Common schema my sql uc 2012
 
Common schema my sql uc 2012
Common schema   my sql uc 2012Common schema   my sql uc 2012
Common schema my sql uc 2012
 

Último

DEV meet-up UiPath Document Understanding May 7 2024 Amsterdam
DEV meet-up UiPath Document Understanding May 7 2024 AmsterdamDEV meet-up UiPath Document Understanding May 7 2024 Amsterdam
DEV meet-up UiPath Document Understanding May 7 2024 AmsterdamUiPathCommunity
 
MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 2024MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 2024MIND CTI
 
AXA XL - Insurer Innovation Award Americas 2024
AXA XL - Insurer Innovation Award Americas 2024AXA XL - Insurer Innovation Award Americas 2024
AXA XL - Insurer Innovation Award Americas 2024The Digital Insurer
 
Apidays New York 2024 - Passkeys: Developing APIs to enable passwordless auth...
Apidays New York 2024 - Passkeys: Developing APIs to enable passwordless auth...Apidays New York 2024 - Passkeys: Developing APIs to enable passwordless auth...
Apidays New York 2024 - Passkeys: Developing APIs to enable passwordless auth...apidays
 
ICT role in 21st century education and its challenges
ICT role in 21st century education and its challengesICT role in 21st century education and its challenges
ICT role in 21st century education and its challengesrafiqahmad00786416
 
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...Jeffrey Haguewood
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerThousandEyes
 
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...DianaGray10
 
Emergent Methods: Multi-lingual narrative tracking in the news - real-time ex...
Emergent Methods: Multi-lingual narrative tracking in the news - real-time ex...Emergent Methods: Multi-lingual narrative tracking in the news - real-time ex...
Emergent Methods: Multi-lingual narrative tracking in the news - real-time ex...Zilliz
 
MS Copilot expands with MS Graph connectors
MS Copilot expands with MS Graph connectorsMS Copilot expands with MS Graph connectors
MS Copilot expands with MS Graph connectorsNanddeep Nachan
 
Ransomware_Q4_2023. The report. [EN].pdf
Ransomware_Q4_2023. The report. [EN].pdfRansomware_Q4_2023. The report. [EN].pdf
Ransomware_Q4_2023. The report. [EN].pdfOverkill Security
 
Spring Boot vs Quarkus the ultimate battle - DevoxxUK
Spring Boot vs Quarkus the ultimate battle - DevoxxUKSpring Boot vs Quarkus the ultimate battle - DevoxxUK
Spring Boot vs Quarkus the ultimate battle - DevoxxUKJago de Vreede
 
Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024The Digital Insurer
 
Artificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : UncertaintyArtificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : UncertaintyKhushali Kathiriya
 
AWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of TerraformAWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of TerraformAndrey Devyatkin
 
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...apidays
 
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024Victor Rentea
 
[BuildWithAI] Introduction to Gemini.pdf
[BuildWithAI] Introduction to Gemini.pdf[BuildWithAI] Introduction to Gemini.pdf
[BuildWithAI] Introduction to Gemini.pdfSandro Moreira
 
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers:  A Deep Dive into Serverless Spatial Data and FMECloud Frontiers:  A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FMESafe Software
 
Architecting Cloud Native Applications
Architecting Cloud Native ApplicationsArchitecting Cloud Native Applications
Architecting Cloud Native ApplicationsWSO2
 

Último (20)

DEV meet-up UiPath Document Understanding May 7 2024 Amsterdam
DEV meet-up UiPath Document Understanding May 7 2024 AmsterdamDEV meet-up UiPath Document Understanding May 7 2024 Amsterdam
DEV meet-up UiPath Document Understanding May 7 2024 Amsterdam
 
MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 2024MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 2024
 
AXA XL - Insurer Innovation Award Americas 2024
AXA XL - Insurer Innovation Award Americas 2024AXA XL - Insurer Innovation Award Americas 2024
AXA XL - Insurer Innovation Award Americas 2024
 
Apidays New York 2024 - Passkeys: Developing APIs to enable passwordless auth...
Apidays New York 2024 - Passkeys: Developing APIs to enable passwordless auth...Apidays New York 2024 - Passkeys: Developing APIs to enable passwordless auth...
Apidays New York 2024 - Passkeys: Developing APIs to enable passwordless auth...
 
ICT role in 21st century education and its challenges
ICT role in 21st century education and its challengesICT role in 21st century education and its challenges
ICT role in 21st century education and its challenges
 
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected Worker
 
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
 
Emergent Methods: Multi-lingual narrative tracking in the news - real-time ex...
Emergent Methods: Multi-lingual narrative tracking in the news - real-time ex...Emergent Methods: Multi-lingual narrative tracking in the news - real-time ex...
Emergent Methods: Multi-lingual narrative tracking in the news - real-time ex...
 
MS Copilot expands with MS Graph connectors
MS Copilot expands with MS Graph connectorsMS Copilot expands with MS Graph connectors
MS Copilot expands with MS Graph connectors
 
Ransomware_Q4_2023. The report. [EN].pdf
Ransomware_Q4_2023. The report. [EN].pdfRansomware_Q4_2023. The report. [EN].pdf
Ransomware_Q4_2023. The report. [EN].pdf
 
Spring Boot vs Quarkus the ultimate battle - DevoxxUK
Spring Boot vs Quarkus the ultimate battle - DevoxxUKSpring Boot vs Quarkus the ultimate battle - DevoxxUK
Spring Boot vs Quarkus the ultimate battle - DevoxxUK
 
Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024
 
Artificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : UncertaintyArtificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : Uncertainty
 
AWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of TerraformAWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of Terraform
 
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...
 
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
 
[BuildWithAI] Introduction to Gemini.pdf
[BuildWithAI] Introduction to Gemini.pdf[BuildWithAI] Introduction to Gemini.pdf
[BuildWithAI] Introduction to Gemini.pdf
 
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers:  A Deep Dive into Serverless Spatial Data and FMECloud Frontiers:  A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
 
Architecting Cloud Native Applications
Architecting Cloud Native ApplicationsArchitecting Cloud Native Applications
Architecting Cloud Native Applications
 

Stored procedure

  • 1. Stored Procedure By Deepak Sharma Software Developer
  • 2. What is Stored Procedure? • A stored procedure is a group of sql statements that has been created and stored in the database. • Stored procedure will accepts input parameters so that a single procedure can be used over network by several clients using different input data.
  • 3. Benefit of Stored Procedure • Stored procedure will reduce network traffic and increase the performance. • If we modify stored procedure all clients will get the updated stored procedure.
  • 4. Types of Stored Procedure 1. System Stored Procedure 2. User Defined Stored Procedure Types of User Defined Stored Procedure:- 1. Non Parameterized Stored Procedure 2. Parameterized Stored Procedure
  • 5. --¤ USER DEFINED PROCEDURE-"NON PARAMETERIZED STORED PROCEDURE" Firstly we have to create table:- • create table contact(id int,name nvarchar(15),age int) • select * from contact • insert into contact select 1,'Deepak',23 union all select 2,'Shipra',23 union all select 3,'Richa',23 union all select 4,'Rashi',23
  • 6. --¤ USER DEFINED PROCEDURE-"NON PARAMETERIZED STORED PROCEDURE" Create Procedure:- • create proc ProcDemo_select as select * from contact Here proc declare as a procedure and you can also write procedure. Fore execute this procedure :- • exec ProcDemo_select
  • 7. --¤ USER DEFINED PROCEDURE - "PARAMETERIZED PROCEDURE" • create proc ProcDemo_insert(@id int, @name nvarchar(15), @age int) as insert into contact values(@id,@name,@age) • exec ProcDemo_insert 4,'Aryan',23 • --or • --ProcDemo_insert 5,'Hello',23 • exec ProcDemo_select • ------------------------------------------------------------------------------------------------------------------- • create proc ProcDemo_update(@id int,@name nvarchar(15), @age int) as update contact set name=@name, age=@age where id=@id • exec ProcDemo_update 4,'Radha',23 • exec ProcDemo_select • ------------------------------------------------------------------------------------------------------------------- • create proc ProcDemo_delete(@id int) as delete from contact where id=@id • exec ProcDemo_delete 4 • exec ProcDemo_select
  • 8. FOR VIEW ALL OF QUERY OF STORED PROCEDURE • sp_helptext ProcDemo_select • sp_helptext ProcDemo_insert • sp_helptext ProcDemo_update • sp_helptext ProcDemo_delete
  • 9. FOR DELETE STORED PROCEDURE • drop proc ProcDemo_select • drop proc ProcDemo_insert • drop proc ProcDemo_update • drop proc ProcDemo_delete
  • 10. NAMING STRORED PROCEDURE OBJECT So some of these may be: • uspInsertPerson - insert a new person record • uspGetAccountBalance - get the balance of an account • uspGetOrderHistory - return list of orders
  • 11. STORED PROCEDURE USING TRY & CATCH BLOCK-:- • CREATE PROCEDURE ProcDemo_TryCatch AS BEGIN TRY SELECT * from contact END TRY BEGIN CATCH SELECT ERROR_NUMBER() AS ErrorNumber, ERROR_SEVERITY() AS ErrorSeverity, ERROR_STATE() AS ErrorState, ERROR_PROCEDURE() AS ErrorProcedure, ERROR_LINE() AS ErrorLine, ERROR_MESSAGE() AS ErrorMessage; END CATCH exec ProcDemo_TryCatch FOR CALCULATING AVERAGE • create proc ProcedureAverage as select AVG(id) as Average from contact • exec ProcedureAverage
  • 12. USING STORED PROCEDURE WITH ASP.NET PAGE WITH TRANSACTION ON .ASPX PAGE-:- create table test(id int,name varchar(20)) select * from test insert test select 1,'Deepak' union all select 2,'Rashi' create proc sp_Test(@id int,@name varchar(20)) as begin try insert into test values(@id,@name) END TRY BEGIN CATCH SELECT ERROR_LINE(),ERROR_NUMBER(),ERROR_PROCEDURE(),ERROR_SEVERITY( ),ERROR_STATE(),ERROR_MESSAGE(); END CATCH drop proc sp_Test
  • 13. allow a developer to work with transaction with two simple statement: ¤ Begin Transaction ¤ Commit Transaction ADO.NET TRANSACTION:- con.Open(); SqlTransaction trans; trans = con.BeginTransaction(); try { cmd = new SqlCommand("sp_Test", con); cmd.CommandType = CommandType.StoredProcedure; cmd.Parameters.AddWithValue("@id", SqlDbType.Int).Value = txtID.Text; cmd.Parameters.AddWithValue("@name", SqlDbType.VarChar).Value = txtName.Text.ToString(); cmd.Transaction = trans; cmd.ExecuteNonQuery(); trans.Commit(); } catch { trans.Rollback(); Label1.Text = "Insert Fail"; } con.Close(); con.Dispose();