What Is a User-defined Function? Scalar Functions –Similar to a built-in function Multi-Statement Table-valued Functions –Content like a stored procedure.

Slides:



Advertisements
Similar presentations
1 Constraints, Triggers and Active Databases Chapter 9.
Advertisements

Index Blocking Factors, Views Rose-Hulman Institute of Technology Curt Clifton.
Stored Procedures and Functions Rose-Hulman Institute of Technology Curt Clifton.
Module 10: Implementing User-defined Functions. Overview What Is a User-defined Function? Defining Examples.
Assertions and Triggers Rose-Hulman Institute of Technology Curt Clifton.
Module 9: Implementing Stored Procedures. Introduction to Stored Procedures Creating Executing Modifying Dropping Using Parameters in Stored Procedures.
Tools of the trade TSQL CIS 407. SQL Server Tools Books on line! Don’t use sql server authentication –Use windows authentication (safer) for developer.
Module 11: Implementing Triggers. Overview Introduction Defining Create, drop, alter triggers How Triggers Work Examples Performance Considerations Analyze.
Module 8: Implementing Views. Overview Introduction Advantages Definition Modifying Data Through Views Optimizing Performance by Using Views.
Topics Views Stored Procedures User Defined Functions Triggers.
IMS 4212: Application Architecture and Intro to Stored Procedures 1 Dr. Lawrence West, Management Dept., University of Central Florida
SQL Review Tonga Institute of Higher Education. SQL Introduction SQL (Structured Query Language) a language that allows a developer to work with data.
Module 8: Implementing Stored Procedures. Introducing Stored Procedures Creating, Modifying, Dropping, and Executing Stored Procedures Using Parameters.
Module 1: Introduction to Transact-SQL
Triggers How triggers work Creating triggers Using triggers to maintain referential integrity Multirow considerations Nesting triggers Rules associated.
SQL Server 7.0 Maintaining Referential Integrity.
T-SQL Transact-SQL is microsoft implementation of SQL. It contains additional programming constracts T-SQL enables you to write programs that contain SQL.
Module 9: Introduction to Programming Objects. Overview Displaying the Text of a Programming Object Introduction to Views Advantages of Views Creating.
Module 4: Managing Security. Overview Implementing an Authentication Mode Assigning Login Accounts to Users and Roles Assigning Permissions to Users and.
Module 3: Retrieving Data. Overview Retrieving Data by Using the SELECT Statement Filtering Data Formatting Result Sets How Queries Are Processed Performance.
SQL SERVER.  DML Triggers  DDL Trigers  INSERT triggers  DELETE triggers  UPDATE triggers  A mix and match of any of the above.
IMS 4212: Intro to SQL 1 Dr. Lawrence West, Management Dept., University of Central Florida Introduction to SQL—Topics Introduction to.
Constraints cis 407 Types of Constraints & Naming Key Constraints Unique Constraints Check Constraints Default Constraints Misc Rules and Defaults Triggers.
Module 4: Implementing Data Integrity
Objectives Database triggers and syntax
06 | Modifying Data in SQL Server Brian Alderman | MCT, CEO / Founder of MicroTechPoint Tobias Ternstrom | Microsoft SQL Server Program Manager.
PL/SQLPL/SQL Oracle10g Developer: PL/SQL Programming Chapter 9 Database Triggers.
IMS 4212: Data Manipulation 1 Dr. Lawrence West, MIS Dept., University of Central Florida Additional Data Manipulation Statements INSERT.
Module 7: Modifying Data. Overview Using Transactions Inserting Data Deleting Data Updating Data Performance Considerations.
Module 7: Implementing Views. Overview Introducing Views Defining and Using Views Using Views to Optimize Performance.
More queries Outer joins and summary queries. Inner and outer joins An Inner join only returns matching rows from two tables –E.g. if I join the customer.
PL/SQLPL/SQL Oracle11g: PL/SQL Programming Chapter 9 Database Triggers.
PL/SQLPL/SQL Oracle10g Developer: PL/SQL Programming Chapter 9 Database Triggers.
G. Green 1.  Options include:  Script Files  already covered  APIs  last course topic  Database-Stored Code  our focus 2.
Creating Stored Procedures, Functions and Triggers Telerik Software Academy Databases.
Learningcomputer.com SQL Server 2008 –Views, Functions and Stored Procedures.
Best Practices Transact-SQL.  Transact-SQL Syntax Elements Batch Directives Comments Identifiers Types of Data Variables System Functions Operators Expressions.
Slide 1 Chapter 7 – Part 3 Stored Procedure, Function &Trigger.
SQL Server 2012 Session: 1 Session: 12 Triggers Data Management Using Microsoft SQL Server.
Ch 5. Introducing More Database Objects. Database Objects Table (ch2) View (ch3) Stored Procedure Trigger Function User-defined types.
IMS 4212: Application Architecture and Intro to Stored Procedures 1 Dr. Lawrence West, Management Dept., University of Central Florida
IMS 4212: Constraints & Triggers 1 Dr. Lawrence West, Management Dept., University of Central Florida Stored Procedures in SQL Server.
Ch 3. Working with Tables and Views. Data type Specify type of data to be entered into a column (text, number, datetime, etc) Unicode (National) Datatypes.
Chapter 13 Triggers. Trigger Overview A trigger is a program unit that is executed (fired) due to an event Event such as updating tables, deleting data.
Ch 7. Working with relational data. Transactions Group of statements executed as a group. If all statements execute successfully, changes are committed.
Module 8: Using Programming Objects for Data Retrieval.
Constraints and Views Chap. 3-5 continued (7 th ed. 5-7)
SQL Triggers, Functions & Stored Procedures Programming Operations.
Module 9: Implementing Functions. Overview Creating and Using Functions Working with Functions Controlling Execution Context.
Module 9: Implementing User-Defined Functions. Overview Introducing User-Defined Functions Implementing User-Defined Functions.
Implementing Functions Advanced Database Dr. AlaaEddin Almabhouh.
Module 5: Working with Subqueries. Writing Basic Subqueries Writing Correlated Subqueries Comparing Subqueries with Joins and Temporary Tables Using Common.
Introduction to Structured Query Language (SQL) By Techandmate.comTechandmate.com Learn SQL Server With US.
Transact SQL (T-SQL) Creating Stored Procedures, Functions and Triggers SoftUni Team Technical Trainers Software University
Trigger used in PosgreSQL
COMP 430 Intro. to Database Systems
Module 3: Retrieving Data
Creating Database Triggers
Implementing Triggers
Module 10: Implementing Triggers
Structured Query Language – The Basics
STORED PROCEDURES AND FUNCTION (9.6.1)
MySQL Joins MySQL joins are used to combine rows from two or more tables. Different SQL JOINs INNER JOIN: Returns all rows when there is at least one match.
Module 5: Implementing Data Integrity by Using Constraints
Overview Implementing Triggers Implementing XML Schemas.
Web Services שפת SQL כתבה: זהבה יעקובסון ליווי מקצועי : ארז קלר
Oracle9i Developer: PL/SQL Programming Chapter 8 Database Triggers.
Prof. Arfaoui. COM390 Chapter 9
Triggers 7/11/2019 See scm-intranet.
Presentation transcript:

What Is a User-defined Function? Scalar Functions –Similar to a built-in function Multi-Statement Table-valued Functions –Content like a stored procedure –Referenced like a view In-Line Table-valued Functions –Similar to a view with parameters –Returns a table as the result of single SELECT statement

Creating a User-defined Function USE Northwind CREATE FUNCTION fn_NewRegion nvarchar(30)) RETURNS nvarchar(30) BEGIN IS NULL = 'Not Applicable' END USE Northwind CREATE FUNCTION fn_NewRegion nvarchar(30)) RETURNS nvarchar(30) BEGIN IS NULL = 'Not Applicable' END Creating a Function

Using a Scalar User-defined Function RETURNS Clause Specifies Data Type Function Is Defined Within a BEGIN and END Block Return Type Is Any Data Type Except text, ntext, image, cursor, or timestamp

Example of a Scalar User-defined Function USE Northwind CREATE FUNCTION fn_DateFormat char(1)) RETURNS Nchar(20) AS BEGIN RETURN CONVERT(Nvarchar(20), + CONVERT(Nvarchar(20), + CONVERT(Nvarchar(20), END USE Northwind CREATE FUNCTION fn_DateFormat char(1)) RETURNS Nchar(20) AS BEGIN RETURN CONVERT(Nvarchar(20), + CONVERT(Nvarchar(20), + CONVERT(Nvarchar(20), END SELECT dbo.fn_DateFormat(GETDATE(), ':') Creating the Function Calling the Function

Example of a Multi-Statement Table-valued Function Creating the Function Calling the Function USE Northwind GO CREATE FUNCTION fn_Employees nvarchar(9)) table (EmployeeID int PRIMARY KEY NOT NULL, [Employee Name] nvarchar(61) NOT NULL) AS BEGIN = 'ShortName' SELECT EmployeeID, LastName FROM Employees ELSE = 'LongName' SELECT EmployeeID, (FirstName + ' ' + LastName) FROM Employees RETURN END USE Northwind GO CREATE FUNCTION fn_Employees nvarchar(9)) table (EmployeeID int PRIMARY KEY NOT NULL, [Employee Name] nvarchar(61) NOT NULL) AS BEGIN = 'ShortName' SELECT EmployeeID, LastName FROM Employees ELSE = 'LongName' SELECT EmployeeID, (FirstName + ' ' + LastName) FROM Employees RETURN END SELECT * FROM dbo.fn_Employees('LongName') Or SELECT * FROM dbo.fn_Employees('ShortName') SELECT * FROM dbo.fn_Employees('LongName') Or SELECT * FROM dbo.fn_Employees('ShortName')

Example of an In-Line Table-valued Function Creating the Function Calling the Function Using a Parameter USE Northwind GO CREATE FUNCTION fn_CustomerNamesInRegion nvarchar(30) ) RETURNS table AS RETURN ( SELECT CustomerID, CompanyName FROM Northwind.dbo.Customers WHERE Region ) USE Northwind GO CREATE FUNCTION fn_CustomerNamesInRegion nvarchar(30) ) RETURNS table AS RETURN ( SELECT CustomerID, CompanyName FROM Northwind.dbo.Customers WHERE Region ) SELECT * FROM fn_CustomerNamesInRegion(N'WA')

What Is a Trigger? Associated with a Table Invoked Automatically Cannot Be Called Directly Is Part of a Transaction

Uses of Triggers Cascade Changes Through Related Tables in a Database Enforce More Complex Data Integrity Than a CHECK Constraint Define Custom Error Messages Maintain Denormalized Data Compare Before and After States of Data Under Modification

Creating Triggers Requires Appropriate Permissions Cannot Contain Certain Statements Use Northwind GO CREATE TRIGGER Empl_Delete ON Employees FOR DELETE AS IF (SELECT COUNT(*) FROM Deleted) > 1 BEGIN RAISERROR( 'You cannot delete more than one employee at a time.', 16, 1) ROLLBACK TRANSACTION END Use Northwind GO CREATE TRIGGER Empl_Delete ON Employees FOR DELETE AS IF (SELECT COUNT(*) FROM Deleted) > 1 BEGIN RAISERROR( 'You cannot delete more than one employee at a time.', 16, 1) ROLLBACK TRANSACTION END

How an INSERT Trigger Works INSERT statement to a table with an INSERT Trigger Defined INSERT [Order Details] VALUES (10525, 2, 19.00, 5, 0.2) INSERT [Order Details] VALUES (10525, 2, 19.00, 5, 0.2) Order Details OrderID ProductID UnitPrice Quantity Discount Insert statement logged insertedinserted TRIGGER Actions Execute Order Details OrderID ProductID UnitPrice Quantity Discount Trigger Code: USE Northwind CREATE TRIGGER OrdDet_Insert ON [Order Details] FOR INSERT AS UPDATE P SET UnitsInStock = (P.UnitsInStock – I.Quantity) FROM Products AS P INNER JOIN Inserted AS I ON P.ProductID = I.ProductID Trigger Code: USE Northwind CREATE TRIGGER OrdDet_Insert ON [Order Details] FOR INSERT AS UPDATE P SET UnitsInStock = (P.UnitsInStock – I.Quantity) FROM Products AS P INNER JOIN Inserted AS I ON P.ProductID = I.ProductID UPDATE P SET UnitsInStock = (P.UnitsInStock – I.Quantity) FROM Products AS P INNER JOIN Inserted AS I ON P.ProductID = I.ProductIDProductsProducts ProductID UnitsInStock … … … … INSERT Statement to a Table with an INSERT Trigger Defined INSERT Statement Logged Trigger Actions Executed

How a DELETE Trigger Works DELETE Statement to a table with a DELETE Trigger Defined DeletedDeleted 4 4 Dairy Products Cheeses 0x15… DELETE statement logged CategoriesCategories CategoryID CategoryName Beverages Condiments Confections Beverages Condiments Confections Description Soft drinks, coffees… Sweet and savory … Desserts, candies, … Soft drinks, coffees… Sweet and savory … Desserts, candies, … Picture 0x15… 0x15…0x15… CheesesDairy Products4 DELETE Categories WHERE CategoryID = 4 DELETE Categories WHERE CategoryID = 4 USE Northwind CREATE TRIGGER Category_Delete ON Categories FOR DELETE AS UPDATE P SET Discontinued = 1 FROM Products AS P INNER JOIN deleted AS d ON P.CategoryID = d.CategoryID USE Northwind CREATE TRIGGER Category_Delete ON Categories FOR DELETE AS UPDATE P SET Discontinued = 1 FROM Products AS P INNER JOIN deleted AS d ON P.CategoryID = d.CategoryID ProductsProducts ProductID Discontinued … … … … Trigger Actions Execute 21 UPDATE P SET Discontinued = 1 FROM Products AS P INNER JOIN deleted AS d ON P.CategoryID = d.CategoryID DELETE Statement to a Table with a DELETE Statement Defined DELETE Statement Logged Trigger Actions Executed

How an UPDATE Trigger Works UPDATE Statement to a table with an UPDATE Trigger Defined UPDATE Employees SET EmployeeID = 17 WHERE EmployeeID = 2 UPDATE Employees SET EmployeeID = 17 WHERE EmployeeID = 2 UPDATE Statement logged as INSERT and DELETE Statements EmployeesEmployees EmployeeID LastName FirstName Title HireDate Davolio Barr Leverling Peacock Davolio Barr Leverling Peacock Nancy Andrew Janet Margaret Nancy Andrew Janet Margaret Sales Rep. R Sales Rep. R Sales Rep. ~~~ 2FullerAndrewVice Pres. ~~~ insertedinserted 17 Fuller Andrew Vice Pres. ~~~ deleteddeleted 2 2 Fuller Andrew Vice Pres. ~~~ TRIGGER Actions Execute USE Northwind GO CREATE TRIGGER Employee_Update ON Employees FOR UPDATE AS IF UPDATE (EmployeeID) BEGIN TRANSACTION RAISERROR ('Transaction cannot be processed.\ ***** Employee ID number cannot be modified.', 10, 1) ROLLBACK TRANSACTION USE Northwind GO CREATE TRIGGER Employee_Update ON Employees FOR UPDATE AS IF UPDATE (EmployeeID) BEGIN TRANSACTION RAISERROR ('Transaction cannot be processed.\ ***** Employee ID number cannot be modified.', 10, 1) ROLLBACK TRANSACTION AS IF UPDATE (EmployeeID) BEGIN TRANSACTION RAISERROR ('Transaction cannot be processed.\ ***** Employee ID number cannot be modified.', 10, 1) ROLLBACK TRANSACTION Transaction cannot be processed. ***** Member number cannot be modified Transaction cannot be processed. ***** Member number cannot be modified EmployeesEmployees EmployeeID LastName FirstName Title HireDate Davolio Barr Leverling Peacock Davolio Barr Leverling Peacock Nancy Andrew Janet Margaret Nancy Andrew Janet Margaret Sales Rep. R Sales Rep. R Sales Rep. ~~~ 2FullerAndrewVice Pres. ~~~ UPDATE Statement to a Table with an UPDATE Trigger Defined UPDATE Statement Logged as INSERT and DELETE Statements Trigger Actions Executed

How an INSTEAD OF Trigger Works Create a View That Combines Two or More Tables CREATE VIEW Customers AS SELECT * FROM CustomersMex UNION SELECT * FROM CustomersGer CREATE VIEW Customers AS SELECT * FROM CustomersMex UNION SELECT * FROM CustomersGerCustomersMexCustomersMex CustomerID CompanyName Country Phone … … ANATR ANTON CENTC ANATR ANTON CENTC Ana Trujill… Antonio M… Centro Co… Ana Trujill… Antonio M… Centro Co… Mexico (5) (5) (5) (5) (5) (5) ~~~ CustomersGerCustomersGer CustomerID CompanyName Country Phone … … ALFKI BLAUS DRACD ALFKI BLAUS DRACD Alfreds Fu… Blauer Se… Drachenb… Alfreds Fu… Blauer Se… Drachenb…Germany GermanyGermany ~~~ INSTEAD OF trigger directs the update to the base tableCustomersCustomers CustomerID CompanyName Country Phone … … ALFKI ANATR ANTON ALFKI ANATR ANTON Alfreds Fu… Ana Trujill… Antonio M… Alfreds Fu… Ana Trujill… Antonio M… Germany Mexico Mexico Germany Mexico Mexico (5) (5) (5) (5) ~~~ Original Insert to the Customers View Does Not Occur UPDATE is Made to the View ALFKI Alfreds Fu…Germany ~~~ALFKI Alfreds Fu…Germany ~~~ INSTEAD OF Trigger Can Be on a Table or View The Action That Initiates the Trigger Does NOT Occur Allows Updates to Views Not Previously Updateable

Examples of Triggers Enforcing Data Integrity Enforcing Business Rules

Enforcing Data Integrity CREATE TRIGGER BackOrderList_Delete ON Products FOR UPDATE AS IF (SELECT BO.ProductID FROM BackOrders AS BO JOIN Inserted AS I ON BO.ProductID = I.Product_ID ) > 0 BEGIN DELETE BO FROM BackOrders AS BO INNER JOIN Inserted AS I ON BO.ProductID = I.ProductID END ProductsProducts ProductID UnitsInStock … … … … Updated BackOrdersBackOrders ProductID UnitsOnOrder … … Trigger Deletes Row

ProductsProducts ProductID UnitsInStock … … … … Enforcing Business Rules Products with Outstanding Orders Cannot Be Deleted IF (Select Count (*) FROM [Order Details] INNER JOIN deleted ON [Order Details].ProductID = deleted.ProductID ) > 0 ROLLBACK TRANSACTION IF (Select Count (*) FROM [Order Details] INNER JOIN deleted ON [Order Details].ProductID = deleted.ProductID ) > 0 ROLLBACK TRANSACTION DELETE statement executed on Product table Trigger code checks the Order Details table Order Details OrderID ProductID UnitPrice Quantity Discount ' Transaction cannot be processed ' ' This product has order history ' ' Transaction cannot be processed ' ' This product has order history ' Transaction rolled backProductsProducts ProductID UnitsInStock … … … …