Ch 5. Introducing More Database Objects
Database Objects Table (ch2) View (ch3) Stored Procedure Trigger Function User-defined types
Stored Procedures A collection of code stored as an object in the database Accepts parameters Allows all T-SQL statements Can be called with EXECUTE statement
Types of Stored Procedures System Stored Procedures T-SQL Stored Procedures CLR Procedures Extended stored procedures
System Stored Procedure Pre-defined stored procedures to perform maintenance and management activities
System Stored Procedures
System Stored Procedure sp_help, xp_logininfo, sp_monitor, sp_who etc…
T-SQL Stored Procedures Benefit: Code Reusability reduce network traffic – centrally stored on the server Permission-based execution – only user with valid permission can execute it Security – Prevent SQL Injection attacks
T-SQL Stored Procedure Create a table using following code CREATE TABLE Employees( EmployeeID int IDENTITY(1,1) Primary key NOT NULL, Employeename nvarchar(200) NULL, EmployeeSSN int NULL, msg nchar(10) NULL ) EmployeeIDEmployeeNameEmployeeSSNmsg
T-SQL Stored Procedure TO create a stored procedure to insert CREATE PROCEDURE InsertEmployee int ) AS INSERT INTO Employees (EmployeeName, EmployeeSSN)
T-SQL Stored Procedure To test our stored procedure: InsertEmployee ‘Tester’, Go InsertEmployee ‘Tester2’, Go InsertEmployee ‘Tester3’, Go
T-SQL Stored Procedure TO create a stored procedure to Update a row CREATE PROCEDURE UpdateEmployee int ) AS UPDATE Employees SET WHERE EmployeeID
T-SQL Stored Procedure To test our stored procedure: UpdateEmployee 0, ‘Update Tester’,
T-SQL Stored Procedure TO create a stored procedure to Delete a row CREATE PROCEDURE DeleteEmployee int ) AS DELETE FROM Employees WHERE EmployeeID
T-SQL Stored Procedure To test our stored procedure: DeleteEmployee 0
CLR Stored Procedure Access to objects/methods outside of MS SQL Server 2005 Uses.Net CLR (Common Language runtime) For complex calculations or methods that require access to objects outside of SQL Server Exercise 5.1
Triggers Group of code that will automatically execute when a certain event occur DML trigger (Data Manipulation Language) - Insert, Update, Delete table opereations DDL Trigger (Data Defination Language) – database/Server events
DML Insert Trigger CREATE TRIGGER trg_Insert ON [dbo].[Employees] FOR INSERT AS int = EmployeeID FROM INSERTED UPDATE Employees SET msg = 'Inserted' WHERE EmployeeID
DML Update Trigger CREATE TRIGGER trg_Update ON [dbo].[Employees] FOR UPDATE AS int = EmployeeID FROM DELETED IF UPDATE(EmployeeName) UPDATE Employees SET msg = 'Updated' WHERE EmployeeID
DML Delete Trigger CREATE TRIGGER trg_Delete ON [dbo].[Employees] FOR DELETE AS int = EmployeeID FROM DELETED ROLLBACK BEGIN TRANSACTION --remove transaction error UPDATE Employees SET msg = 'Deleted' WHERE EmployeeID
DML Instead of Trigger Completely ‘skip’ the insert/update/delete event, then execute the trigger Still populates INSERTED, DELETED internal table
DML Instead of Trigger CREATE TRIGGER trg_InsteadUpdate ON [dbo].[Employees] INSTEAD OF UPDATE AS BEGIN IF UPDATE(EmployeeName) int = EmployeeID FROM DELETED UPDATE Employees SET msg = 'I_Update' WHERE EmployeeID END
DML Instead of Trigger CREATE TRIGGER trg_InsteadDelete ON [dbo].[Employees] INSTEAD OF DELETE AS BEGIN int = EmployeeID FROM DELETED UPDATE Employees SET msg = 'I_Deleted' WHERE EmployeeID END
DDL Trigger A group of code to automatically fire on any DDL event (create table, drop table …) New in SQL 2005 Page
DDL Trigger CREATE TRIGGER trg_block_ddl ON DATABASE FOR DDL_DATABASE_LEVEL_EVENTS AS RAISERROR('database locked for ddl events',16,1) ROLLBACK TRANSACTION
Trigger Nesting A trigger event that was fired by another trigger SQL Server supports up to 32 levels, after which the trigger will be canceled Disable Trigger Nesting SP_CONFIGURE ‘nested_triggers’,0 RECONFIGURE
Trigger Recursion Direct Recursion – Trigger perform a statement that will cause itself to be fired InDirect Recursion – Trigger1 perform a statement that will fire Trigge2 which will fire Trigger1, repeat
Trigger Recursion CREATE TRIGGER [trg_RecursiveInsert] ON [dbo].[Employees] FOR INSERT AS nvarchar(200) int = = EmployeeSSN FROM Employees
Disable Trigger Recursion Disable (Direct) Recursive Trigger ALTER DATABASE databasename SET RECURSIVE_TRIGGER OFF Disable (inDirect) Recursive Trigger SP_CONFIGURE ‘nested_triggers’,0 RECONFIGURE
Functions Similar to a stored procedure except it can be called within a SELECT statement Type of Function: Scalar Function Table-valued function Built-in function CLR function
Functions Create this table CREATE TABLE [dbo].[EmployeeInfo] ( [EmployeeInfoID] [int] IDENTITY(1,1) PRIMARY KEY NOT NULL, [EmployeeID] [int] NOT NULL, [DOB] [datetime] NULL, )
Scalar Functions CREATE FUNCTION [dbo].[Age] datetime ) RETURNS int AS BEGIN int = END GO
Scalar Functions To test our function: SELECT *, dbo.Age(EmployeeInfo.DOB) FROM Employee INNER JOIN EmployeeInfo ON Employee.EmployeeID = EmployeeInfo.EmployeeID
Table-valued Functions CREATE FUNCTION [dbo].[getTable] () RETURNS TABLE AS ( SELECT Employee.EmployeeName, dbo.Age(EmployeeInfo.DOB) AS AGE FROM Employee INNER JOIN EmployeeInfo ON Employee.EmployeeID = EmployeeInfo.EmployeeID )
Table-valued Functions Can be used to return a whole table To test our table-valued function select * from getTable()
Built-in Functions Much like built-in stored procedures
Function - Determinism Deterministic function - always return the same value Non-Deterministic Function – may return different value each time
Function - Determinism A Non-Deterministic function CREATE FUNCTION getTime int ) RETURNS datetime AS BEGIN RETURN GetDate()) END GO
Function - Determinism A Deterministic function CREATE FUNCTION int ) RETURNS int AS BEGIN RETURN END GO
User-Defined Types Create an alias to an existing data type Only have ability to set length and NOT NULL option Created using SP_addtype
User-Defined Types Open a new database query in SYBEX EXEC sp_addtype ssn, ‘VARCHAR(11)’, ‘NOT NULL’ Create a table with user defined type CREATE TABLE Employees (EmployeeID int identity (1,1), Employeename nvarchar(200), DepartmentID int, EmployeeSSN ssn)