SlideShare a Scribd company logo
1 of 8
-----------------------User Degine Function---------------
----------------------------------------------------------
-- Type 1 > Scaler Functions : Returns single value.
--Ex: Factorial of Given No.
CREATE FUNCTION UDF_Factorial( @num int)
RETURNS int
AS
BEGIN
DECLARE @fact int
SET @fact=1
WHILE @num != 0
BEGIN
SET @fact=@fact * @num
SET @num=@num-1
END
RETURN @fact
END
-----------------------------------------------------------------
--Execute User Define Function
SELECT dbo.UDF_Factorial(5) as Factorial
------------------------------------------------------------------
--Ex: Function to Find Employee MAX Salary of Given Dept
CREATE FUNCTION UDF_getMaxSal(@Deptid int)
RETURNS NUMERIC(10,2)
AS
BEGIN
DECLARE @MaxSal NUMERIC(10,5)
SET @MaxSal=(SELECT TOP 1 Salary FROM tblEmployee WHERE DeptId=@Deptid ORDER
BY Salary DESC)
RETURN @MaxSal
END
GO
--Execution of UDF in SELECT Statment
SELECT EmpId,EmpName,Address,Deptid,Salary FROM tblEmployee WHERE
Salary=dbo.UDF_getMaxSal(2)
-- Type 2 > Inline Table Valued Function : Returns Table Object
--Ex: Function to Return Record of Emplyees whose Salary > given salry
CREATE FUNCTION UDF_getEmpRecordsAboveGivenSal(@Salary int)
RETURNS Table
AS
return (SELECT EmpId,EmpName,Address,Gender,Salary FROM tblEmployee WHERE
Salary > @Salary)
GO
-----------------------------------------------------------------------------
-- Execution
SELECT * FROM dbo.UDF_getEmpRecordsAboveGivenSal(25000)
-- Type 3 > Multi Statement Table Valued Function :
-- Explicitly defines the structure of the table to return.
-- Defines column names and datatypes in the RETURNS clause.
--Ex: Fuction to get Employee Records with Dept Name
CREATE FUNCTION getEmpByDeptName()
RETURNS @EmpWithDept Table
(
EmpId int,
EmpName varchar(50),
DeptName varchar(50)
)
AS
BEGIN
INSERT INTO @EmpWithDept SELECT e.EmpId,e.Empname,d.DeptName FROM
tblDepartment d INNER JOIN tblEmployee e ON d.DeptId=e.DeptId
return
END
GO
-----------------------------------------------------------------------------
-- Execute Multi Statement Table Valued Function
SELECT * FROM dbo.getEmpByDeptName()
--Modify or Alter UDF like Follows
Alter FUNCTION getEmpByDeptName(@DeptName varchar(50))
RETURNS @EmpWithDept Table
(
EmpId int,
EmpName varchar(50),
DeptName varchar(50)
)
AS
BEGIN
INSERT INTO @EmpWithDept SELECT e.EmpId,e.Empname,d.DeptName FROM
tblDepartment d INNER JOIN tblEmployee e ON d.DeptId=e.DeptId WHERE
DeptName=@Deptname
UPDATE @EmpWithDept SET DeptName='DOT NET' WHERE DeptName='.NET'
return
END
GO
-----------------------------------------------------------------------------
---------------------------------------------------
-- Execute Multi Statement Table Valued Function
SELECT * FROM dbo.getEmpByDeptName('.NET')
----------------------------------Triggers-----------------------------------
-----------------------------------------------------------------------------
--Defination : A trigger is an action that is performed behind-the-scenes
when an event occurs on a table.
-- Types of Trigger: 1) Instead of/Before 2) After/For
-- There are Two Tables with Field and Diffrent name one is tblPersone and
another is tblPersonUpdate
SELECT * FROM tblPerson
SELECT * FROM tblPersonUpdate
-----------------------------------------------------------------------------
--Inserting Records into tblPerson
INSERT INTO tblPerson
VALUES('Vinay','Sayaji,Indore',Convert(Varchar,GETDATE(),114))
INSERT INTO tblPerson VALUES('Rahul','Vijay
Nagar,Indore',Convert(Varchar,GETDATE(),114))
INSERT INTO tblPerson
VALUES('Hitesh','Khargone',Convert(Varchar,GETDATE(),114))
SELECT * FROM tblPerson
SELECT * FROM tblPersonUpdate
--Creating Trigger on Table tblPerson After Update will Insert Old Record
into tblPersonUpdate
CREATE TRIGGER UDT_PersonUpdate
ON tblPerson
After UPDATE
AS
DECLARE @id int;
DECLARE @name varchar(50);
DECLARE @address varchar(50);
DECLARE @time varchar(50);
select @id=U.id from deleted U;
select @name=U.name from deleted U;
select @address=U.address from deleted U;
select @time=U.time from deleted U;
BEGIN
INSERT INTO
tblPersonUpdate(id,name,address,time)VALUES(@id,@name,@address,@time)
PRINT 'Record Has been Inserted into tblPersonUpdate'
END
--Now Updating in Table tblPersone
UPDATE tblPerson SET address='Bhopal' WHERE id=3
-----------------------------------------------------------------------------
--Now Updated Records in tblPerson and tblPersonUpdate
SELECT * FROM tblPerson
SELECT * FROM tblPersonUpdate

More Related Content

What's hot

Performance Enhancements In Postgre Sql 8.4
Performance Enhancements In Postgre Sql 8.4Performance Enhancements In Postgre Sql 8.4
Performance Enhancements In Postgre Sql 8.4
HighLoad2009
 
Tems 8 Basic steps for beginners
Tems 8 Basic steps for beginners Tems 8 Basic steps for beginners
Tems 8 Basic steps for beginners
Syed Muhammad Zaidi
 
Les08-Oracle
Les08-OracleLes08-Oracle
Les08-Oracle
suman1248
 

What's hot (20)

Les06 Subqueries
Les06 SubqueriesLes06 Subqueries
Les06 Subqueries
 
Les01
Les01Les01
Les01
 
Les01 Writing Basic Sql Statements
Les01 Writing Basic Sql StatementsLes01 Writing Basic Sql Statements
Les01 Writing Basic Sql Statements
 
Les03
Les03Les03
Les03
 
Sql5
Sql5Sql5
Sql5
 
Les02
Les02Les02
Les02
 
Les03 Single Row Function
Les03 Single Row FunctionLes03 Single Row Function
Les03 Single Row Function
 
12c Database TEMPORAL VALIDITY & FLASHBACK ARCHIVE Testing
12c Database TEMPORAL VALIDITY & FLASHBACK ARCHIVE Testing12c Database TEMPORAL VALIDITY & FLASHBACK ARCHIVE Testing
12c Database TEMPORAL VALIDITY & FLASHBACK ARCHIVE Testing
 
MERGE SQL Statement: Lesser Known Facets
MERGE SQL Statement: Lesser Known FacetsMERGE SQL Statement: Lesser Known Facets
MERGE SQL Statement: Lesser Known Facets
 
Quick reference for mongo shell commands
Quick reference for mongo shell commandsQuick reference for mongo shell commands
Quick reference for mongo shell commands
 
Oracle ERP Personalization for control master items list
Oracle ERP Personalization for control master items listOracle ERP Personalization for control master items list
Oracle ERP Personalization for control master items list
 
Pro PostgreSQL
Pro PostgreSQLPro PostgreSQL
Pro PostgreSQL
 
Input output
Input outputInput output
Input output
 
Performance Enhancements In Postgre Sql 8.4
Performance Enhancements In Postgre Sql 8.4Performance Enhancements In Postgre Sql 8.4
Performance Enhancements In Postgre Sql 8.4
 
Loops
LoopsLoops
Loops
 
Tems 8 Basic steps for beginners
Tems 8 Basic steps for beginners Tems 8 Basic steps for beginners
Tems 8 Basic steps for beginners
 
Les10
Les10Les10
Les10
 
Les09
Les09Les09
Les09
 
Les08-Oracle
Les08-OracleLes08-Oracle
Les08-Oracle
 
Single row functions
Single row functionsSingle row functions
Single row functions
 

Viewers also liked (7)

Uas bahasa indonesia iis astuti
Uas bahasa indonesia iis astutiUas bahasa indonesia iis astuti
Uas bahasa indonesia iis astuti
 
Martin luther king jr
Martin luther king jrMartin luther king jr
Martin luther king jr
 
Love
LoveLove
Love
 
Cancun proyecto ingles yanela
Cancun proyecto ingles yanelaCancun proyecto ingles yanela
Cancun proyecto ingles yanela
 
Analisis regresi-sederhana
Analisis regresi-sederhanaAnalisis regresi-sederhana
Analisis regresi-sederhana
 
Week 9 video editing
Week 9   video editingWeek 9   video editing
Week 9 video editing
 
Ag Leader Product Catalog - 2013
Ag Leader Product Catalog - 2013Ag Leader Product Catalog - 2013
Ag Leader Product Catalog - 2013
 

Similar to Queries assignment udf_and_triggers

SQL WORKSHOP::Lecture 9
SQL WORKSHOP::Lecture 9SQL WORKSHOP::Lecture 9
SQL WORKSHOP::Lecture 9
Umair Amjad
 
Database management system file
Database management system fileDatabase management system file
Database management system file
Ankit Dixit
 
Mysqlppt
MysqlpptMysqlppt
Mysqlppt
Reka
 
Ramco C Question Paper 2003
Ramco  C  Question  Paper 2003Ramco  C  Question  Paper 2003
Ramco C Question Paper 2003
ncct
 
you need to complete the r code and a singlepage document c.pdf
you need to complete the r code and a singlepage document c.pdfyou need to complete the r code and a singlepage document c.pdf
you need to complete the r code and a singlepage document c.pdf
adnankhan605720
 

Similar to Queries assignment udf_and_triggers (20)

4sem dbms(1)
4sem dbms(1)4sem dbms(1)
4sem dbms(1)
 
Les09 Manipulating Data
Les09 Manipulating DataLes09 Manipulating Data
Les09 Manipulating Data
 
Database Management System
Database Management SystemDatabase Management System
Database Management System
 
EvolveExecutionPlans.pdf
EvolveExecutionPlans.pdfEvolveExecutionPlans.pdf
EvolveExecutionPlans.pdf
 
SQL WORKSHOP::Lecture 9
SQL WORKSHOP::Lecture 9SQL WORKSHOP::Lecture 9
SQL WORKSHOP::Lecture 9
 
SQLQueries
SQLQueriesSQLQueries
SQLQueries
 
Database management system file
Database management system fileDatabase management system file
Database management system file
 
Function and types
Function  and typesFunction  and types
Function and types
 
Sql dml & tcl 2
Sql   dml & tcl 2Sql   dml & tcl 2
Sql dml & tcl 2
 
ZFINDALLZPROGAM
ZFINDALLZPROGAMZFINDALLZPROGAM
ZFINDALLZPROGAM
 
[Pgday.Seoul 2019] Citus를 이용한 분산 데이터베이스
[Pgday.Seoul 2019] Citus를 이용한 분산 데이터베이스[Pgday.Seoul 2019] Citus를 이용한 분산 데이터베이스
[Pgday.Seoul 2019] Citus를 이용한 분산 데이터베이스
 
Oracle dbms_xplan.display_cursor format
Oracle dbms_xplan.display_cursor formatOracle dbms_xplan.display_cursor format
Oracle dbms_xplan.display_cursor format
 
SQL Macros - Game Changing Feature for SQL Developers?
SQL Macros - Game Changing Feature for SQL Developers?SQL Macros - Game Changing Feature for SQL Developers?
SQL Macros - Game Changing Feature for SQL Developers?
 
Mysqlppt
MysqlpptMysqlppt
Mysqlppt
 
Ramco C Question Paper 2003
Ramco  C  Question  Paper 2003Ramco  C  Question  Paper 2003
Ramco C Question Paper 2003
 
12c SQL Plan Directives
12c SQL Plan Directives12c SQL Plan Directives
12c SQL Plan Directives
 
Les09[1]Manipulating Data
Les09[1]Manipulating DataLes09[1]Manipulating Data
Les09[1]Manipulating Data
 
Dbmsmanual
DbmsmanualDbmsmanual
Dbmsmanual
 
SAV
SAVSAV
SAV
 
you need to complete the r code and a singlepage document c.pdf
you need to complete the r code and a singlepage document c.pdfyou need to complete the r code and a singlepage document c.pdf
you need to complete the r code and a singlepage document c.pdf
 

Recently uploaded

Artificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and MythsArtificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and Myths
Joaquim Jorge
 

Recently uploaded (20)

From Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationFrom Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
 
Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024
 
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
 
Tech Trends Report 2024 Future Today Institute.pdf
Tech Trends Report 2024 Future Today Institute.pdfTech Trends Report 2024 Future Today Institute.pdf
Tech Trends Report 2024 Future Today Institute.pdf
 
2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...
 
[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdf[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdf
 
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law DevelopmentsTrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
 
Exploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone ProcessorsExploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone Processors
 
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, AdobeApidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
 
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
 
Tata AIG General Insurance Company - Insurer Innovation Award 2024
Tata AIG General Insurance Company - Insurer Innovation Award 2024Tata AIG General Insurance Company - Insurer Innovation Award 2024
Tata AIG General Insurance Company - Insurer Innovation Award 2024
 
Partners Life - Insurer Innovation Award 2024
Partners Life - Insurer Innovation Award 2024Partners Life - Insurer Innovation Award 2024
Partners Life - Insurer Innovation Award 2024
 
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemkeProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
 
The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024
 
Artificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and MythsArtificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and Myths
 
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
 
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...
 
Driving Behavioral Change for Information Management through Data-Driven Gree...
Driving Behavioral Change for Information Management through Data-Driven Gree...Driving Behavioral Change for Information Management through Data-Driven Gree...
Driving Behavioral Change for Information Management through Data-Driven Gree...
 
Data Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt RobisonData Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt Robison
 
Understanding Discord NSFW Servers A Guide for Responsible Users.pdf
Understanding Discord NSFW Servers A Guide for Responsible Users.pdfUnderstanding Discord NSFW Servers A Guide for Responsible Users.pdf
Understanding Discord NSFW Servers A Guide for Responsible Users.pdf
 

Queries assignment udf_and_triggers

  • 1. -----------------------User Degine Function--------------- ---------------------------------------------------------- -- Type 1 > Scaler Functions : Returns single value. --Ex: Factorial of Given No. CREATE FUNCTION UDF_Factorial( @num int) RETURNS int AS BEGIN DECLARE @fact int SET @fact=1 WHILE @num != 0 BEGIN SET @fact=@fact * @num SET @num=@num-1 END RETURN @fact END ----------------------------------------------------------------- --Execute User Define Function SELECT dbo.UDF_Factorial(5) as Factorial ------------------------------------------------------------------
  • 2. --Ex: Function to Find Employee MAX Salary of Given Dept CREATE FUNCTION UDF_getMaxSal(@Deptid int) RETURNS NUMERIC(10,2) AS BEGIN DECLARE @MaxSal NUMERIC(10,5) SET @MaxSal=(SELECT TOP 1 Salary FROM tblEmployee WHERE DeptId=@Deptid ORDER BY Salary DESC) RETURN @MaxSal END GO --Execution of UDF in SELECT Statment SELECT EmpId,EmpName,Address,Deptid,Salary FROM tblEmployee WHERE Salary=dbo.UDF_getMaxSal(2)
  • 3. -- Type 2 > Inline Table Valued Function : Returns Table Object --Ex: Function to Return Record of Emplyees whose Salary > given salry CREATE FUNCTION UDF_getEmpRecordsAboveGivenSal(@Salary int) RETURNS Table AS return (SELECT EmpId,EmpName,Address,Gender,Salary FROM tblEmployee WHERE Salary > @Salary) GO ----------------------------------------------------------------------------- -- Execution SELECT * FROM dbo.UDF_getEmpRecordsAboveGivenSal(25000)
  • 4. -- Type 3 > Multi Statement Table Valued Function : -- Explicitly defines the structure of the table to return. -- Defines column names and datatypes in the RETURNS clause. --Ex: Fuction to get Employee Records with Dept Name CREATE FUNCTION getEmpByDeptName() RETURNS @EmpWithDept Table ( EmpId int, EmpName varchar(50), DeptName varchar(50) ) AS BEGIN INSERT INTO @EmpWithDept SELECT e.EmpId,e.Empname,d.DeptName FROM tblDepartment d INNER JOIN tblEmployee e ON d.DeptId=e.DeptId return END GO ----------------------------------------------------------------------------- -- Execute Multi Statement Table Valued Function SELECT * FROM dbo.getEmpByDeptName()
  • 5. --Modify or Alter UDF like Follows Alter FUNCTION getEmpByDeptName(@DeptName varchar(50)) RETURNS @EmpWithDept Table ( EmpId int, EmpName varchar(50), DeptName varchar(50) ) AS BEGIN INSERT INTO @EmpWithDept SELECT e.EmpId,e.Empname,d.DeptName FROM tblDepartment d INNER JOIN tblEmployee e ON d.DeptId=e.DeptId WHERE DeptName=@Deptname UPDATE @EmpWithDept SET DeptName='DOT NET' WHERE DeptName='.NET' return END GO ----------------------------------------------------------------------------- --------------------------------------------------- -- Execute Multi Statement Table Valued Function SELECT * FROM dbo.getEmpByDeptName('.NET')
  • 6. ----------------------------------Triggers----------------------------------- ----------------------------------------------------------------------------- --Defination : A trigger is an action that is performed behind-the-scenes when an event occurs on a table. -- Types of Trigger: 1) Instead of/Before 2) After/For -- There are Two Tables with Field and Diffrent name one is tblPersone and another is tblPersonUpdate SELECT * FROM tblPerson SELECT * FROM tblPersonUpdate ----------------------------------------------------------------------------- --Inserting Records into tblPerson INSERT INTO tblPerson VALUES('Vinay','Sayaji,Indore',Convert(Varchar,GETDATE(),114)) INSERT INTO tblPerson VALUES('Rahul','Vijay Nagar,Indore',Convert(Varchar,GETDATE(),114)) INSERT INTO tblPerson VALUES('Hitesh','Khargone',Convert(Varchar,GETDATE(),114))
  • 7. SELECT * FROM tblPerson SELECT * FROM tblPersonUpdate --Creating Trigger on Table tblPerson After Update will Insert Old Record into tblPersonUpdate CREATE TRIGGER UDT_PersonUpdate ON tblPerson After UPDATE AS DECLARE @id int; DECLARE @name varchar(50); DECLARE @address varchar(50); DECLARE @time varchar(50); select @id=U.id from deleted U; select @name=U.name from deleted U; select @address=U.address from deleted U; select @time=U.time from deleted U; BEGIN INSERT INTO tblPersonUpdate(id,name,address,time)VALUES(@id,@name,@address,@time) PRINT 'Record Has been Inserted into tblPersonUpdate' END
  • 8. --Now Updating in Table tblPersone UPDATE tblPerson SET address='Bhopal' WHERE id=3 ----------------------------------------------------------------------------- --Now Updated Records in tblPerson and tblPersonUpdate SELECT * FROM tblPerson SELECT * FROM tblPersonUpdate