Upload
ngodang
View
218
Download
0
Embed Size (px)
Citation preview
Stored Procedures
• Benefits of Stored Procedures:
1. Precompiled execution
2. Reduced client/server traffic
3. Efficient reuse of code and programming abstraction
4. Enhanced security controls
• A stored procedure is an already written SQL statement that is saved in the database.
Functions
• Benefits of Functions :
1. Reusing code from one program to another, cutting down on program development time
2. Hiding the SQL details, allowing database developers to worry about SQL and application developers to deal only in higher-level languages
3. Centralize maintenance, allowing you to make business logic changes in a single place that automatically affect all dependent applications
Stored Procedures vs Functions
• A function is a subprogram written to perform certain computations and return a single value.
• Functions must return a value (using the RETURN keyword, but for stored procedures this is not compulsory).
• Stored procedures can use RETURN keyword but without any value being passed.
• Functions could be used in SELECT statements, provided they don’t do any data manipulation. However, procedures cannot be included in SELECT statements.
• A function can have only IN parameters, while stored procedures may have OUT or INOUT parameters.
• A stored procedure can return multiple values using the OUT parameter or return no value at all.
Trigger
• Triggers offer database developers and administrators a tremendous degree of flexibility. They are, quite simply, stored procedures that may be configured to automatically execute when certain events take place.
Stored Procedures Syntax
CREATE PROC[EDURE] [schema.]
procedure [ { @parameter [schema.]
data_type } [VARYING ] [ = default ]
[ OUT[PUT] ] ] [ ,...n ] [WITH Option
[,...n ]]
AS { sql_statement [;][ ...n ] | EXTERNAL
NAME assembly.class.method }
[;]
ALTER PROCEDURE
EXEC – Execute Procedure
DROP PROCEDURE
Functions Syntax
CREATE FUNCTION [schema.] function
( [@parameter [ AS ][type_schema.]
parameter_data_type [= default ]
[ ,...n ]
])
RETURNS return_clause...
[;]
ALTER FUNCTION
DROP FUNCTION
What Kind of User-Defined Functions ?
• There are three types of User-Defined functions in SQL Server and they are :
1. Scalar
2. Inline Table-Valued
3. Multi-statement Table-valued
Trigger DML
• Syntax for DML Trigger (INSERT, UPDATE, or DELETE)
CREATE TRIGGER [ schema.] trigger
ON { table | view }
[WITH trigger_option [ ,...n ] ]
{FOR | AFTER | INSTEAD OF}
{[INSERT] [, ] [UPDATE] [, ] [DELETE]}
[WITH APPEND ] [ NOT FOR REPLICATIO]
AS { sql_statement [;] [,...n] |
EXTERNAL NAME
assembly.class.method [;] }
Trigger DDL
• Syntax for DDL Trigger (CREATE, ALTER, DROP, GRANT, DENY, REVOKE, or UPDATE STATISTICS)
CREATE TRIGGER trigger
ON { ALL SERVER | DATABASE }
[WITH trigger_option [,...n] ]
{FOR | AFTER } { event_type |
event_group } [,...n]
AS { sql_statement [;] [,...n] |
EXTERNAL NAME
assembly.class.method [;] }
Stored Procedures Samples (1)
CREATE PROCEDURE [dbo].[GetProducts] AS
SELECT ProductID, ProductName FROM Products
-------------------------------------
EXEC GetProducts
Stored Procedured Examples (2)
CREATE PROCEDURE OrderSummary @MaxQuantity INT OUTPUT AS
SELECT Ord.EmployeeID,
SummSales = SUM(OrDet.UnitPrice * OrDet.Quantity)
FROM Orders AS Ord JOIN [Order Details] AS OrDet
ON (Ord.OrderID = OrDet.OrderID)
GROUP BY Ord.EmployeeID
ORDER BY Ord.EmployeeID
SELECT @MaxQuantity = MAX(Quantity) FROM [Order Details]
RETURN (SELECT SUM(Quantity) FROM [Order Details])
Stored Procedures Samples (3)
DECLARE @OrderSum INT
DECLARE @LargestOrder INT
EXEC @OrderSum = OrderSummary
@MaxQuantity = @LargestOrder OUTPUT
PRINT 'The size of the largest single order was: '
+ CONVERT(CHAR(6), @LargestOrder)
PRINT 'The sum of the quantities ordered was: '
+ CONVERT(CHAR(6), @OrderSum)
Stored Procedures Samples (4)
CREATE PROCEDURE CustomerOrder
@CustID nvarchar(5)
AS
SELECT orderID,CustomerId,OrderDate
FROM Orders
WHERE CustomerID=@CustID
-------------------------------------
EXEC CustomerOrder @CustID='WILMK'
Function Examples – Scalar (1)
CREATE FUNCTION whichContinent (@Country nvarchar(15))
RETURNS varchar(30)
AS
BEGIN
declare @Return varchar(30)
select @return = case @Country
when 'Argentina' then 'South America'
when 'Belgium' then 'Europe'
when 'Brazil' then 'South America'
when 'Canada' then 'North America'
when 'Denmark' then 'Europe'
when 'Finland' then 'Europe'
when 'France' then 'Europe'
else 'Unknown'
end
return @return
end
Function Examples - Scalar (2)
PRINT dbo.WhichContinent('USA')
-------------------------------------
SELECT dbo.WhichContinent(Customers.Country),
customers.* FROM customers
Function Examples – Scalar (3)
CREATE FUNCTION Job_Category(@Contact nvarchar(30))
RETURNS varchar(30)
AS
BEGIN
declare @return varchar(30)
select @return =
(case when @Contact like 'Owner%' then 'Owner'
else
(case when @Contact like 'Sales%' then 'Sales'
else
(case when @Contact like 'Marketing%' then 'Marketing'
else
(case when @Contact like 'Accounting%' then 'Accounting'
else 'Unknown'
END) END) END) END)
return @return
END
Function Examples – Scalar (4)
ALTER FUNCTION Price_Range(@Price money)
RETURNS varchar(30)
AS
BEGIN
declare @return varchar(30)
SELECT @return = case
when @Price<=0 then 'not for resale'
when @Price>0 AND @Price<=25 then 'under 25'
when @Price>25 AND @Price<=50 then 'under 50'
else 'over 50'
END
return @return
END
Function Examples - Inline Table-Valued (1)
CREATE FUNCTION CustomersByContinent
(@Continent varchar(30))
RETURNS TABLE
AS
RETURN
SELECT
dbo.WhichContinent(Customers.Country) as continent,
customers.*
FROM customers
WHERE dbo.WhichContinent(Customers.Country) =
@Continent
Function Examples - Inline Table-Valued (2)
SELECT * FROM CustomersbyContinent('North America')
SELECT * FROM CustomersByContinent('South America')
SELECT * FROM CustomersbyContinent('Unknown')
Function Examples - Multi-statement Table-valued (1) CREATE FUNCTION dbo.customersbycountry( @Country varchar(15)
)
RETURNS
@CustomersbyCountryTab table (
[CustomerID] [nchar] (5),
[CompanyName] [nvarchar] (40),
[ContactName] [nvarchar] (30),
[ContactTitle] [nvarchar] (30),
[Address] [nvarchar] (60),
[City] [nvarchar] (15),
[PostalCode] [nvarchar] (10),
[Country] [nvarchar] (15),
[Phone] [nvarchar] (24),
[Fax] [nvarchar] (24) )
AS
BEGIN
Function Examples - Multi-statement Table-valued (2)
INSERT INTO @CustomersByCountryTab
SELECT [CustomerID],
[CompanyName],
[ContactName],
[ContactTitle],
[Address],
[City],
[PostalCode],
[Country],
[Phone],
[Fax]
FROM [Northwind].[dbo].[Customers]
WHERE country = @Country
Function Examples - Multi-statement Table-valued (3)
DECLARE @cnt INT
SELECT @cnt = COUNT(*) FROM @customersbyCountryTab
IF @cnt = 0
INSERT INTO @CustomersByCountryTab (
[CustomerID],
[CompanyName],
[ContactName],
[ContactTitle],
[Address],
[City],
[PostalCode],
[Country],
[Phone],
[Fax] )
VALUES ('','No Companies Found','','','','','','','','')
RETURN
END
Function Examples - Multi-statement Table-valued (4)
SELECT * FROM dbo.customersbycountry('USA')
SELECT * FROM dbo.customersbycountry('CANADA')
SELECT * FROM dbo.customersbycountry('ADF')
Trigger Examples (1)
CREATE TABLE dbo.AuditTrail
( AuditTrailID Int IDENTITY (1, 1) NOT NULL,
TableName VarChar (50) NOT NULL,
ActionTaken Char (1) NOT NULL,
ActionUser VarChar (50) NOT NULL,
ActionDate DateTime NOT NULL
)
ON [PRIMARY]
Column Datatype NULL
AuditTrailID Identity Not allowed
TableName VarChar(50) Not allowed
ActionTaken Char(1) Not allowed
ActionUser VarChar(50) Not Allowed
ActionDate DateTime Not Allowed
Trigger Examples (2)
CREATE TRIGGER [AuditInsertUpdate] ON dbo.Products
FOR INSERT, UPDATE
AS
INSERT INTO AuditTrail (TableName, ActionTaken,
ActionUser, ActionDate)
VALUES ('Products', 'I', User_Name(), GetDate())
-------------------------------------
CREATE TRIGGER [AuditDelete] ON dbo.Products
FOR DELETE
AS
INSERT INTO AuditTrail (TableName, ActionTaken,
ActionUser, ActionDate)
VALUES ('Products', 'D', User_Name(), GetDate())
Trigger Examples (3)
UPDATE dbo.Products SET UnitPrice = 1
WHERE ProductID = 1
SELECT * FROM dbo.AuditTrail
Trigger - Inserted and Deleted tables
• DML trigger statements use two special tables: the deleted table and the inserted tables.
• The deleted table stores copies of the affected rows during DELETE and UPDATE statements
• The inserted table stores copies of the affected rows during INSERT and UPDATE statements
Trigger Examples (4)
CREATE TABLE [dbo].[TriggerTest]
([au_id] [int] NULL,
[au_name] [varchar] (50))
-------------------------------------
CREATE TRIGGER tr_InsertConcatName ON authors
FOR INSERT AS
DECLARE @AuthorID VARCHAR(11)
DECLARE @ConcatName VARCHAR(50)
SELECT @AuthorID = (SELECT au_id FROM Inserted)
SELECT @ConcatName = (SELECT au_lName + ', ' +
au_fName FROM Inserted)
INSERT TriggerTest values (@AuthorID,@ConcatName)
-------------------------------------
INSERT authors (au_id, au_lname, au_fname, contract)
VALUES ('123-45-6789', 'Woody', 'Buck', 1)
Trigger Examples (5)
CREATE TRIGGER tr_UpdateConcatName ON authors
FOR UPDATE AS
DECLARE @AuthorID VARCHAR(11)
DECLARE @NewConcatName VARCHAR(50)
SELECT @AuthorID = (SELECT au_id FROM Inserted)
SELECT @NewConcatName = (SELECT au_lName + ', ' +
au_fName FROM Inserted)
UPDATE TriggerTest SET au_name = @NewConcatName WHERE
au_id = @AuthorID
-------------------------------------
UPDATE authors SET au_fname = 'Greg'
WHERE au_id = '123-45-6789'
Trigger Examples (6)
CREATE TRIGGER tr_DeleteConcatName
ON authors FOR DELETE AS
DECLARE @AuthorID VARCHAR(11)
SELECT @AuthorID =
(SELECT au_id FROM Deleted)
DELETE FROM TriggerTest WHERE
au_id = @AuthorID
-------------------------------------
DELETE FROM authors WHERE au_lname = 'Woody'