0% found this document useful (0 votes)
2 views

sql4

The document outlines a training module on advanced databases and SQL querying, led by Yaroslav Dobrianskyi, a lead software engineer with extensive experience. It covers key topics such as SQL views, computed columns, stored procedures, user-defined functions, and triggers, along with practical instructions for creating and modifying views using SQL Server Management Studio and Transact-SQL. The document also includes guidelines for participant engagement during the training session.

Uploaded by

and311003
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views

sql4

The document outlines a training module on advanced databases and SQL querying, led by Yaroslav Dobrianskyi, a lead software engineer with extensive experience. It covers key topics such as SQL views, computed columns, stored procedures, user-defined functions, and triggers, along with practical instructions for creating and modifying views using SQL Server Management Studio and Transact-SQL. The document also includes guidelines for participant engagement during the training session.

Uploaded by

and311003
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 147

Module “DBMS

Basics”
Submodule “Advanced Databases and SQL
Querying”
Yaroslav Dobrianskyi
Lead Software Engineer

CONFIDENTIAL | © 2020 EPAM Systems, Inc.


Recommendations

1 MUTE YOUR MIC

2 ASK QUESTIONS IN CHAT

3 DURATION: 3 HOURS

4 COFFEE BREAK: 10-15 MINUTES

5 Q&A AFTER EACH MODULE

6 TEAMS QUESTIONS CHANNEL

CONFIDENTIAL | © 2020 EPAM Systems, Inc. 2


YA R O S L AV D O B R I A N S K Y I
Lead Software Engineer

• 13 years experience in software development


• Worked at different positions -> DBA, DB Development, ETL,
Python Developer
• Worked at EPAM in 2015-2019 years, joined second time in
2021

CONFIDENTIAL | © 2020 EPAM Systems, Inc. 3


Agenda

1. SQL Views
2. SQL Computed Columns.
3. SQL Stored Procedures
4. SQL User Defined Functions (UDF)
5. SQL Triggers

CONFIDENTIAL | © 2020 EPAM Systems, Inc. 4


SQL VIEWS

CONFIDENTIAL | © 2020 EPAM Systems, Inc. 5


Concept of Views
[AdventureWorks2019].[HumanResources].[Employee]

CONFIDENTIAL | © 2020 EPAM Systems, Inc.


Concept of Views
[AdventureWorks2019].[HumanResources].[Employee]

CONFIDENTIAL | © 2020 EPAM Systems, Inc.


Concept of Views
[AdventureWorks2019].[HumanResources].[Employee]

You can create your own table, but this means you need to maintain 2 tables now
CONFIDENTIAL | © 2020 EPAM Systems, Inc.
View shows only the necessary columns that you need

• View is a virtual table based on the result-set of an


SQL statement

• A view contains rows and columns, just like a real


table. The fields in a view are fields from one or more
real tables in the database

• You can add SQL functions, WHERE, and JOIN


statements to a view and present the data as if the
data were coming from one single table

CONFIDENTIAL | © 2020 EPAM Systems, Inc. 9


View shows only the necessary columns that you need

• View is a virtual table based on the result-set of an


SQL statement

• A view contains rows and columns, just like a real


table. The fields in a view are fields from one or more
real tables in the database
So, we can give access to a view and
deny access to the table
• You can add SQL functions, WHERE, and JOIN
statements to a view and present the data as if the
data were coming from one single table

CONFIDENTIAL | © 2020 EPAM Systems, Inc. 10


Purposes?

• A view can be used for the following purposes:


• To focus, simplify, and customize the perception each
user has of the database.
• As a security mechanism by allowing users to access
data through the view, without granting the users
permissions to directly access the underlying base
tables.

CONFIDENTIAL | © 2020 EPAM Systems, Inc. 11


Types of Views
INDEXED VIEWS PA R T I T I O N E D V I E W S SYSTEM VIEWS

• An indexed view is a • A partitioned view joins • System views expose


view that has been horizontally partitioned catalog metadata
materialized. You index data from a set of
a view by creating a member tables
unique clustered index
on it

CONFIDENTIAL | © 2020 EPAM Systems, Inc. 12


Indexed Views

• The first index created on a view must be a unique clustered index. After the unique clustered index
has been created, you can create more nonclustered indexes.
• Creating a unique clustered index on a view improves query performance because the view is stored
in the database in the same way a table with a clustered index is stored.

CONFIDENTIAL | © 2020 EPAM Systems, Inc. 13


Before You Begin
The following steps are required to create an indexed view and are critical to the successful
implementation of the indexed view:

1. Verify the SET options are correct for all existing tables that will be referenced in the view
2. Verify that the SET options for the session are set correctly before you create any tables and the view
3. Verify that the view definition is deterministic
4. Create the view by using the WITH SCHEMABINDING option
5. Create the unique clustered index on the view

More information on requirements for creation clustered view can be found here
https://docs.microsoft.com/en-us/sql/relational-databases/views/create-indexed-views

CONFIDENTIAL | © 2020 EPAM Systems, Inc. 14


Before You Begin

The following steps are required to create an indexed view and are critical to the successful
implementation of the indexed view:

1. Verify the SET options are correct for all existing tables that will be referenced in the view
2. Verify that the SET options for the session are set correctly before you create any tables and the view
3. Verify that the view definition is deterministic
4. Create the view by using the WITH SCHEMABINDING option
5. Create the unique clustered index on the view

CREATE VIEW view_name


WITH SCHEMABINDING AS
SELECT column1, column2, ...
FROM table_name
GO

CREATE UNIQUE CLUSTERED INDEX view_name


ON view_name(<index_key_columns>)

CONFIDENTIAL | © 2020 EPAM Systems, Inc. 15


Partitioned Views

• It’s a view that combines the full results of a


number of physical tables that are logically CREATE VIEW view_name
separated by a boundary AS
• This makes the data appear as if from one table SELECT columns...
FROM Table1
UNION ALL
SELECT columns...
FROM Table2
UNION ALL
SELECT columns...
FROM Table3

CONFIDENTIAL | © 2020 EPAM Systems, Inc. 16


System Views

• Select Database -> Views -> Systems Views

CONFIDENTIAL | © 2020 EPAM Systems, Inc. 17


Create Views. Using SQL Server Management Studio

1. In Object Explorer, expand the database where you want to


create your new view.
2. Right-click the Views folder, then click New View....
3. In the Add Table dialog box, select the element or elements
that you want to include in your new view from one of the
following tabs: Tables, Views, Functions, and Synonyms.
4. Click Add, then click Close.
5. In the Diagram Pane, select the columns or other elements
to include in the new view.
6. In the Criteria Pane, select additional sort or filter criteria for
the columns.
7. On the File menu, click Save view name.
8. In the Choose Name dialog box, enter a name for the new
view and click OK.

CONFIDENTIAL | © 2020 EPAM Systems, Inc. 18


Create Views. Using Transact-SQL

1. In Object Explorer, connect to an instance of Database


Engine.
2. On the Standard bar, click New Query.
3. Copy and paste the following example into the query window
and click Execute.

CONFIDENTIAL | © 2020 EPAM Systems, Inc. 19


Create Views. Using Transact-SQL

1. In Object Explorer, connect to an instance of Database


Engine.
2. On the Standard bar, click New Query.
3. Copy and paste the following example into the query window
and click Execute.

CREATE VIEW Syntax


CREATE VIEW view_name AS
SELECT column1, column2, ...
FROM table_name
WHERE condition;

CONFIDENTIAL | © 2020 EPAM Systems, Inc. 20


Create Views. Using Transact-SQL

1. In Object Explorer, connect to an instance of Database


Engine.
2. On the Standard bar, click New Query.
3. Copy and paste the following example into the query window
USE AdventureWorks2019
and click Execute. GO

CREATE VIEW HumanResources.EmployeeInfo


AS
SELECT LoginID, OrganizationLevel, JobTitle, BirthDate,
MaritalStatus, Gender, HireDate, SalariedFlag,
VacationHours, SickLeaveHours
FROM HumanResources.Employee

GO

CONFIDENTIAL | © 2020 EPAM Systems, Inc. 21


Modify Views

• After you define a view, you can modify its definition in SQL Server 2019 (15.x) without dropping and re-
creating the view by using SQL Server Management Studio or Transact-SQL

CONFIDENTIAL | © 2020 EPAM Systems, Inc. 22


Modify Views. Using SQL Server Management Studio

1. In Object Explorer, click the plus sign next to the database where your view is
located and then click the plus sign next to the Views folder.

2. Right-click on the view you wish to modify and select Design.


3. In the diagram pane of the query designer, make changes to the view in one
or more of the following ways:
1. Select or clear the check boxes of any elements you wish to add or
remove.
2. Right-click within the diagram pane, select Add Table..., and then
select the additional columns you want to add to the view from
the Add Table dialog box.
3. Right-click the title bar of the table you wish to remove and
select Remove.
4. On the File menu, click Save view name.

CONFIDENTIAL | © 2020 EPAM Systems, Inc. 23


Modify Views. Using Transact-SQL

1. In Object Explorer, connect to an instance of Database Engine.


2. On the Standard bar, click New Query.

3. Copy and paste the following example into the query window and
click Execute. The example first creates a view and then modifies the
view by using ALTER VIEW. A WHERE clause is added to the view
definition.

CONFIDENTIAL | © 2020 EPAM Systems, Inc. 24


Modify Views. Using Transact-SQL

1. In Object Explorer, connect to an instance of Database Engine.


2. On the Standard bar, click New Query.

3. Copy and paste the following example into the query window and
click Execute. The example first creates a view and then modifies the
view by using ALTER VIEW. A WHERE clause is added to the view
definition.

MODIFY VIEW Syntax


ALTER VIEW view_name AS
SELECT column1, column2, ...
FROM table_name
WHERE condition;

CONFIDENTIAL | © 2020 EPAM Systems, Inc. 25


Modify Views. Using Transact-SQL

USE AdventureWorks2019 ;
GO 1. In Object Explorer, connect to an instance of Database Engine.
CREATE VIEW HumanResources.EmployeeInfo
AS 2. On the Standard bar, click New Query.
SELECT LoginID, OrganizationLevel, JobTitle,
3. Copy and paste the following example into the query window and
BirthDate, MaritalStatus, Gender, HireDate,
SalariedFlag, VacationHours, SickLeaveHours click Execute. The example first creates a view and then modifies the
FROM HumanResources.Employee view by using ALTER VIEW. A WHERE clause is added to the view
GO definition.
-- Modify the view by adding a WHERE clause to

MODIFY VIEW Syntax


limit the rows returned
ALTER VIEW [HumanResources].[EmployeeInfo]
AS
SELECT LoginID, OrganizationLevel, JobTitle, ALTER VIEW view_name AS
BirthDate, MaritalStatus, Gender, HireDate, SELECT column1, column2, ...
SalariedFlag, VacationHours, SickLeaveHours
FROM HumanResources.Employee FROM table_name
WHERE HireDate < CONVERT(DATETIME,'20100101’) WHERE condition;
GO

CONFIDENTIAL | © 2020 EPAM Systems, Inc. 26


Modify Data Through a View (Update)

• You can modify the data of an underlying base table in SQL Server by using SQL Server Management Studio or Transact-SQL

CONFIDENTIAL | © 2020 EPAM Systems, Inc. 27


Modify Data Through a View (Update)

• You can modify the data of an underlying base table in SQL Server by using SQL Server Management Studio or Transact-SQL
• You can modify the data of an underlying base table through a view, as long as the following conditions are true:

• Any modifications, including UPDATE, INSERT, and DELETE statements, must reference columns from only one base table.

CONFIDENTIAL | © 2020 EPAM Systems, Inc. 28


Modify Data Through a View (Update)

• You can modify the data of an underlying base table in SQL Server by using SQL Server Management Studio or Transact-SQL
• You can modify the data of an underlying base table through a view, as long as the following conditions are true:

• Any modifications, including UPDATE, INSERT, and DELETE statements, must reference columns from only one base table.
• The columns being modified in the view must directly reference the underlying data in the table columns. The columns cannot be
derived in any other way, such as through the following:
• An aggregate function: AVG, COUNT, SUM, MIN, MAX, GROUPING, STDEV, STDEVP, VAR, and VARP.
• A computation. The column cannot be computed from an expression that uses other columns. Columns that are formed by
using the set operators UNION, UNION ALL, CROSSJOIN, EXCEPT, and INTERSECT amount to a computation and are also not
updatable.

CONFIDENTIAL | © 2020 EPAM Systems, Inc. 29


Modify Data Through a View (Update)

• You can modify the data of an underlying base table in SQL Server by using SQL Server Management Studio or Transact-SQL
• You can modify the data of an underlying base table through a view, as long as the following conditions are true:

• Any modifications, including UPDATE, INSERT, and DELETE statements, must reference columns from only one base table.
• The columns being modified in the view must directly reference the underlying data in the table columns. The columns cannot be
derived in any other way, such as through the following:
• An aggregate function: AVG, COUNT, SUM, MIN, MAX, GROUPING, STDEV, STDEVP, VAR, and VARP.
• A computation. The column cannot be computed from an expression that uses other columns. Columns that are formed by
using the set operators UNION, UNION ALL, CROSSJOIN, EXCEPT, and INTERSECT amount to a computation and are also not
updatable.
• The columns being modified are not affected by GROUP BY, HAVING, or DISTINCT clauses.

CONFIDENTIAL | © 2020 EPAM Systems, Inc. 30


Modify Data Through a View (Update)

IMPORTANT! IT WILL CHANGE DATA IN BASE TABLE!

CONFIDENTIAL | © 2020 EPAM Systems, Inc. 31


Update Views. Using SQL Server Management Studio

1. In Object Explorer, expand the database that contains the view


and then expand Views.

2. Right-click the view and select Edit Top 200 Rows.

3. You may need to modify the SELECT statement in the SQL pane
to return the rows to be modified.

4. In the Results pane, locate the row to be changed or deleted. To


delete the row, right-click the row and select Delete. To change
data in one or more columns, modify the data in the column.

IMPORTANT!! You cannot delete a row if the view references more than one base table.
You can only update columns that belong to a single base table.

5. To insert a row, scroll down to the end of the rows and insert the
new values.
IMPORTANT! You cannot insert a row if the view references more than one base table.

CONFIDENTIAL | © 2020 EPAM Systems, Inc. 32


Update Views. Using Transact-SQL

1. In Object Explorer, connect to an instance of Database


Engine.
2. On the Standard bar, click New Query.
3. Copy and paste the following example into the query window
and click Execute.

CONFIDENTIAL | © 2020 EPAM Systems, Inc. 33


Update Views. Using Transact-SQL

1. In Object Explorer, connect to an instance of Database


Engine.
2. On the Standard bar, click New Query.
3. Copy and paste the following example into the query window
and click Execute.

UPDATE VIEW Syntax


UPDATE view_name
SET column1 = value1, column2 = value2, ...
WHERE condition;

CONFIDENTIAL | © 2020 EPAM Systems, Inc. 34


Update Views. Using Transact-SQL

1. In Object Explorer, connect to an instance of Database


Engine. USE [AdventureWorks2019]
2. On the Standard bar, click New Query. GO
3. Copy and paste the following example into the query window
and click Execute.
UPDATE [HumanResources].[EmployeeInfo]
This example changes the value in the MaritalStatus column SET MaritalStatus = 'M'
for a specific employee by referencing columns in the WHERE LoginID = 'adventure-works\ken0'
view [HumanResources].[EmployeeInfo]

CONFIDENTIAL | © 2020 EPAM Systems, Inc. 35


Update Views. Using Transact-SQL

1. In Object Explorer, connect to an instance of Database


Engine.
2. On the Standard bar, click New Query. USE AdventureWorks2019 ;
3. Copy and paste the following example into the query window GO
and click Execute. UPDATE
HumanResources.vEmployeeDepartmentHistory
This example changes the value in the StartDate and EndDate SET StartDate = ‘20120203', EndDate = GETDATE()
columns for a specific employee by referencing columns in the WHERE LastName = N'Smith' AND FirstName =
view HumanResources.vEmployeeDepartmentHistory. This 'Samantha';
view returns values from two tables. This statement succeeds GO
because the columns being modified are from only one of the
base tables

CONFIDENTIAL | © 2020 EPAM Systems, Inc. 36


How to insert table data through a view?

1. In Object Explorer, connect to an instance of Database


Engine.
2. On the Standard bar, click New Query.
3. Copy and paste the following example into the query
window and click Execute.

CONFIDENTIAL | © 2020 EPAM Systems, Inc. 37


How to insert table data through a view?

1. In Object Explorer, connect to an instance of Database


Engine.
2. On the Standard bar, click New Query.
3. Copy and paste the following example into the query
window and click Execute.

INSERT INTO VIEW Syntax


INSERT INTO view_name (column1, column2, ...)
VALUES (value1, value2, ...)

CONFIDENTIAL | © 2020 EPAM Systems, Inc. 38


How to insert table data through a view?

1. In Object Explorer, connect to an instance of Database


Engine.
2. On the Standard bar, click New Query. USE AdventureWorks2019 ;
3. Copy and paste the following example into the query GO
window and click Execute. INSERT INTO
HumanResources.vEmployeeDepartmentHistory
The example inserts a new row into the base (Department, GroupName)
table HumanResources.Department by specifying the VALUES ('MyDepartment', 'MyGroup');
relevant columns from the view GO
HumanResources.vEmployeeDepartmentHistory. The
statement succeeds because only columns from a single base
table are specified and the other columns in the base table
have default values.

CONFIDENTIAL | © 2020 EPAM Systems, Inc. 39


Get Information About a View

• You can gain information about a view's definition or properties in SQL Server 2019 (15.x) by using
SQL Server Management Studio or Transact-SQL
• You may need to see the definition of the view to understand how its data is derived from the
source tables or to see the data defined by the view

CONFIDENTIAL | © 2020 EPAM Systems, Inc. 40


To get the definition and properties of a view

1. In Object Explorer, connect to an instance of Database Engine.


2. On the Standard bar, click New Query.
3. Copy and paste one of the following examples into the query window and click Execute.

USE AdventureWorks2019;
GO
SELECT OBJECT_DEFINITION (OBJECT_ID('HumanResources.vEmployee')) AS ObjectDefinition;
GO

CONFIDENTIAL | © 2020 EPAM Systems, Inc. 41


To get the dependencies of a view

1. In Object Explorer, connect to an instance of Database Engine.


2. On the Standard bar, click New Query.
3. Copy and paste the following example into the query window and click Execute.

USE AdventureWorks2019;
GO
SELECT OBJECT_NAME(referencing_id) AS referencing_entity_name,
o.type_desc AS referencing_desciption,
referenced_schema_name,
referenced_entity_name,
COALESCE(COL_NAME(referenced_id, referenced_minor_id), '(n/a)') AS referenced_column_name
FROM sys.sql_expression_dependencies AS sed
INNER JOIN sys.objects AS o ON sed.referencing_id = o.object_id
WHERE referencing_id = OBJECT_ID(N'Production.vProductAndDescription');
GO

CONFIDENTIAL | © 2020 EPAM Systems, Inc. 42


To get the dependencies of a view

Using SQL Server Management Studio

CONFIDENTIAL | © 2020 EPAM Systems, Inc. 43


Rename Views

You can rename a view in SQL Server 2019 (15.x) by using SQL Server Management Studio or
Transact-SQL

CONFIDENTIAL | © 2020 EPAM Systems, Inc. 44


Rename Views

You can rename a view in SQL Server 2019 (15.x) by using SQL Server Management Studio or
Transact-SQL

NOTE: If you rename a view, code and applications that depend on the view may fail. These
include other views, queries, stored procedures, user-defined functions, and client
applications. Note that these failures will cascade

CONFIDENTIAL | © 2020 EPAM Systems, Inc. 45


Rename Views

Using SQL Server Management Studio

CONFIDENTIAL | © 2020 EPAM Systems, Inc. 46


Rename Views. Using Transact-SQL

While you can use sp_rename to change the name of


the view,

BUT there is a recommendation to delete the existing


view and then re-create it with the new name

EXEC sp_rename
@objname = 'HumanResources.EmployeeInfo',
@newname = 'EmployeeInfos';

CONFIDENTIAL | © 2020 EPAM Systems, Inc. 47


Delete Views

You can delete (drop) views in SQL Server 2019 (15.x) by using SQL Server Management Studio or
Transact-SQL

CONFIDENTIAL | © 2020 EPAM Systems, Inc. 48


Delete Views

You can delete (drop) views in SQL Server 2019 (15.x) by using SQL Server Management Studio or
Transact-SQL

NOTE:
When you drop a view, the definition of the view and other information about the view is deleted
from the system catalog
Any view on a table that is dropped by using DROP TABLE must be dropped explicitly by using DROP
VIEW

CONFIDENTIAL | © 2020 EPAM Systems, Inc. 49


Delete Views. Using SQL Server Management Studio

1. In Object Explorer, expand the database


that contains the view you want to delete,
and then expand the Views folder.
2. Right-click the view you want to delete
and click Delete.
3. In the Delete Object dialog box, click OK.

CONFIDENTIAL | © 2020 EPAM Systems, Inc. 50


Delete Views. Using Transact-SQL

1. In Object Explorer, connect to an


instance of Database Engine.
2. On the Standard bar, click New Query.
3. Copy and paste the following example
into the query window and click Execute.

The example deletes the specified view only


if the view already exists.

USE AdventureWorks2019 ;
GO
IF OBJECT_ID ('HumanResources.EmployeeInfos', 'V') IS NOT NULL
DROP VIEW HumanResources.EmployeeInfos;
GO

CONFIDENTIAL | © 2020 EPAM Systems, Inc. 51


Limitations and Disadvantages of Views in SQL Server

WE CANNOT PASS PARAMETERS TO SQL


1
SERVER VIEW S

CANNOT USE AN ORDER BY CLAUSE WITH VIEWS


2
WITHOUT SPECIFYING FOR XML, OFFSET OR TOP

THE VIEWS CANNOT BE CREATED BASED ON


3
TEMPORARY TABLES IN SQL SERVER

A VIEW CAN HAVE A MAXIMUM OF 1,024


4
COLUMNS

A VIEW CAN BE CREATED ONLY IN THE


4
CURRENT DATABASE

CONFIDENTIAL | © 2020 EPAM Systems, Inc. 52


SQL Computed COLUMNS

CONFIDENTIAL | © 2020 EPAM Systems, Inc.


Concept of computed columns

• [AdventureWorks2019].[Person].[Person]

CONFIDENTIAL | © 2020 EPAM Systems, Inc. 54


Concept of computed columns

• [AdventureWorks2019].[Person].[Person]

FullName = FirstName + MiddleName + LastName

CONFIDENTIAL | © 2020 EPAM Systems, Inc. 55


FullName = FirstName + MiddleName + LastName

CONFIDENTIAL | © 2020 EPAM Systems, Inc. 56


FullName = FirstName + MiddleName + LastName

CONFIDENTIAL | © 2020 EPAM Systems, Inc. 57


What is a computed column?

• A computed column is a virtual column that is not physically stored in the table
• A computed column expression can use data from other columns to calculate a value for
the column to which it belongs

CONFIDENTIAL | © 2020 EPAM Systems, Inc. 58


Specify Computed Columns in a Table. Using Transact-SQL

T O A D D A C O M P U T E D C O L U M N W H E N C R E AT I N G A T A B L E

• The following example creates a table with a computed column that multiplies the value in the QtyAvailable
column times the value in the UnitPrice column.

InventoryValue = QtyAvailable * UnitPrice

CONFIDENTIAL | © 2020 EPAM Systems, Inc. 59


Specify Computed Columns in a Table. Using Transact-SQL

T O A D D A C O M P U T E D C O L U M N W H E N C R E AT I N G A T A B L E

• The following example creates a table with a computed column that multiplies the value in the QtyAvailable
column times the value in the UnitPrice column.

CREATE TABLE dbo.Products


(
ProductID int IDENTITY (1,1) NOT NULL
, QtyAvailable smallint
, UnitPrice money
, InventoryValue AS QtyAvailable * UnitPrice
)

-- Insert values into the table


InventoryValue = QtyAvailable * UnitPrice INSERT INTO dbo.Products (QtyAvailable, UnitPrice)
VALUES (25, 2.00), (10, 1.5)

-- Display the rows in the table


SELECT ProductID, QtyAvailable, UnitPrice,
InventoryValue
FROM dbo.Products

CONFIDENTIAL | © 2020 EPAM Systems, Inc. 60


Specify Computed Columns in a Table. Using Transact-SQL

TO A D D A N E W C O M P U T E D C O L U M N TO A N E X I S T I N G TA B L E

• The following example adds a new column to the table created in the previous example

ALTER TABLE dbo.Products ADD RetailValue AS (QtyAvailable * UnitPrice * 1.5)

CONFIDENTIAL | © 2020 EPAM Systems, Inc. 61


Specify Computed Columns in a Table. Using Transact-SQL

TO CH ANGE AN E X IST ING COMPUT ED COLUMN

• The following example modifies the column added in the previous example

ALTER TABLE dbo.Products DROP COLUMN RetailValue


ALTER TABLE dbo.Products ADD RetailValue AS (QtyAvailable * UnitPrice * 1.3)

CONFIDENTIAL | © 2020 EPAM Systems, Inc. 62


Persisted computed columns

• Computed columns can be persisted. It means that SQL Server physically stores the data of the
computed columns on disk.
• When you query the data from the persisted computed columns, SQL Server just needs to retrieve
data without doing any calculation. This avoids calculation overhead with the cost of extra storage

CONFIDENTIAL | © 2020 EPAM Systems, Inc. 63


Persisted computed columns

((CONVERT([int],CONVERT([char](8),getdate(),(112)))-CONVERT([char](8),[Birthdate],(112)))/(10000))

CONFIDENTIAL | © 2020 EPAM Systems, Inc. 64


Persisted computed columns. Result

CONFIDENTIAL | © 2020 EPAM Systems, Inc. 65


Limitations and Disadvantages of Computed Columns

A C O M P U T E D C O L U M N C A N N OT B E U S E D A S
1
A D E FA U LT

C A N N OT B E U S E D A S F O R E I G N K E Y
2
CONSTRAINT DEFINITION

C A N N OT B E U S E D W I T H A N OT N U L L
3
CONSTRAINT DEFINITION

A C O M P U T E D C O L U M N C A N N OT B E T H E
4
TA R G E T O F A N I N S E R T O R U P D AT E

CONFIDENTIAL | © 2020 EPAM Systems, Inc. 66


But…

However, a computed column can be used as a key column in


an index or as part of any PRIMARY KEY or UNIQUE constraint

For example, if the table has integer columns a and b, the


computed column a + b may be indexed

CONFIDENTIAL | © 2020 EPAM Systems, Inc. 67


SQL STORED Procedures

CONFIDENTIAL | © 2020 EPAM Systems, Inc.


Definition of Stored Procedure

A stored procedure is a prepared SQL code that you can save, so the code can be reused over and over again
So if you have an SQL query that you write over and over again, save it as a stored procedure, and then just call it to
execute it
You can also pass parameters to a stored procedure, so that the stored procedure can act based on the parameter
value(s) that is passed
Stored procedure can also use INSERT , UPDATE and DELETE stratements as part of it’s SQL code

A stored procedure (sometimes called a proc, storp, StoPro, StoredProc, StoreProc, sp or SP) is actually stored in the
database data dictionary

CONFIDENTIAL | © 2020 EPAM Systems, Inc. 69


Benefits of Using Stored Procedures

• Reduced server/client network traffic – the commands in a procedure are executed as a


single batch of code

• Stronger security – the procedure controls what processes and activities are performed and
protects the underlying database objects

• Reuse of code – eliminates needless rewrites of the same code

• Easier maintenance – when client applications call procedures and keep database operations
in the data tier, only the procedures must be updated for any changes in the underlying
database

• Improved performance – by default, a procedure compiles the first time it is executed and
creates an execution plan that is reused for subsequent executions

CONFIDENTIAL | © 2020 EPAM Systems, Inc. 70


Types of Stored Procedures

• User-defined
• Temporary
• System

CONFIDENTIAL | © 2020 EPAM Systems, Inc. 71


Types of Stored Procedures

• User-defined – a user-defined procedure can be created in a user-defined database

• Temporary – the temporary procedures are like a permanent procedure, except temporary
procedures are stored in tempdb

• System – system procedures are included with SQL Server. They are logically appear in
the sys schema of every system- and user-defined database

CONFIDENTIAL | © 2020 EPAM Systems, Inc. 72


Types of Stored Procedures

• With no parameters
• With one parameter
• With multiple parameters

CONFIDENTIAL | © 2020 EPAM Systems, Inc. 73


User-defined Stored Procedures

Stored Procedure Syntax


CREATE PROCEDURE procedure_name
AS
sql_statement

Execute a Stored Procedure

EXEC procedure_name

CONFIDENTIAL | © 2020 EPAM Systems, Inc. 74


User-defined Stored Procedures

Stored Procedure Syntax with params


CREATE PROCEDURE procedure_name CREATE PROCEDURE procedure_name @param1 datatype,
AS ...
sql_statement AS
sql_statement

Execute a Stored Procedure with params

EXEC procedure_name EXEC procedure_name @param1 = ‘London’, ...

CONFIDENTIAL | © 2020 EPAM Systems, Inc. 75


Create a Stored Procedure. Using SQL Server Management Studio

1. Expand Databases, expand


the AdventureWorks2019 database, and then
expand Programmability.
2. Right-click Stored Procedures, and then click New Stored
Procedure.

CONFIDENTIAL | © 2020 EPAM Systems, Inc. 76


Create a Stored Procedure (no params). Using Transact-SQL

1. From the File menu, click New Query.


2. Create your own query.
CREATE PROCEDURE PERSON_EMAIL
AS

SET NOCOUNT ON --number of rows off


SELECT FirstName, LastName, EmailAddress
FROM Person.Person AS P
INNER JOIN Person.EmailAddress AS EA
ON P.BusinessEntityID = EA.BusinessEntityID

EXECUTE PERSON_EMAIL
EXEC PERSON_EMAIL

CONFIDENTIAL | © 2020 EPAM Systems, Inc. 77


Create a Stored Procedure (with params). Using Transact -SQL
CREATE PROCEDURE PERSON_FN_EMAIL
1. From the File menu, click New Query. @FirstName varchar(50)
2. Create your own query. AS
SET NOCOUNT ON
SELECT FirstName, LastName, EmailAddress
FROM Person.Person AS P
INNER JOIN Person.EmailAddress AS EA
ON P.BusinessEntityID =
EA.BusinessEntityID
WHERE P.FirstName = @FirstName

EXEC PERSON_FN_EMAIL @FirstName =


'Alexandra'
EXEC PERSON_FN_EMAIL 'Alexandra'

CONFIDENTIAL | © 2020 EPAM Systems, Inc. 78


Default params. Using Transact-SQL
CREATE PROCEDURE PERSON_FN_EMAIL
1. From the File menu, click New Query. @FirstName varchar(50) = 'Alexandra'
2. Create your own query. AS
SET NOCOUNT ON
SELECT FirstName, LastName, EmailAddress
FROM Person.Person AS P
INNER JOIN Person.EmailAddress AS EA
ON P.BusinessEntityID =
EA.BusinessEntityID
WHERE P.FirstName = @FirstName

EXEC PERSON_FN_EMAIL

CONFIDENTIAL | © 2020 EPAM Systems, Inc. 79


OUTPUT params. Using Transact-SQL

1. From the File menu, click New Query.


2. Create your own query. CREATE PROCEDURE procedure_name @param1 datatype,
@param2 datatype OUTPUT, ...
AS
sql_statement

DECLARE @param2 DATATYPE


EXEC procedure_name @param1 = ‘London’,
@param2 OUTPUT ...

CONFIDENTIAL | © 2020 EPAM Systems, Inc. 80


RETURN values. Using Transact-SQL

1. From the File menu, click New Query.


2. Create your own query. CREATE PROCEDURE procedure_name
AS
sql_statement
RETURN ...

DECLARE @return_value DATATYPE


EXEC @return_value = procedure_name
SELECT @return_value

CONFIDENTIAL | © 2020 EPAM Systems, Inc. 81


Settings while creating a procedure

• ANSI_NULLS
• This parameter controls what happens when you try to use any comparison operator other than IS to NULL. When it is ON, these comparisons
follow the standard which says that comparisons with NULL always fail (because it is not a value, but a flag) and returns FALSE. When this
parameter is OFF (really not recommended), you can successfully use it as a value and use =, <>, etc. on it and return TRUE as appropriate.

SET ANSI_NULLS ON

SELECT * FROM dbo.Person


WHERE MiddleName = 'NULL'

SELECT * FROM dbo.Person


WHERE MiddleName IS NULL
CONFIDENTIAL | © 2020 EPAM Systems, Inc. 82
Settings while creating a procedure

• QUOTED_IDENTIFIER
• This parameter determines how the quotation marks ".." are interpreted by the SQL compiler. If QUOTED_IDENTIFIER is ON, then
quotes are treated like parentheses ([...]) and can be used to quote SQL object names such as table names, column names, etc. If it
is OFF (not recommended), then quotes are treated as apostrophes ('..') and can be used to quote text strings in SQL commands.

SET QUOTED_IDENTIFIER ON
UPDATE "dbo"."Person"
SET "FirstName" = 'Vik'
WHERE "MiddleName" = 'N'

CONFIDENTIAL | © 2020 EPAM Systems, Inc. 83


Modify a Stored Procedure. Using SQL Server Management Studio

1. Expand Databases, expand


the AdventureWorks2019 database, and then
expand Programmability.
2. Expand Stored Procedures, right-click the procedure to
modify, and then click Modify.

CONFIDENTIAL | © 2020 EPAM Systems, Inc. 84


Modify a Stored Procedure. Using Transact-SQL

1. From the File menu, click New Query.


2. Create your own query to modify a proc.

ALTER PROCEDURE procedure_name


AS
sql_statement

CONFIDENTIAL | © 2020 EPAM Systems, Inc. 85


DELETE Stored Procedure. Using SQL Server Management Studio

1. Expand Databases, expand


the AdventureWorks2019 database, and then
expand Programmability.
2. Expand Stored Procedures, right-click the procedure to
modify, and then click Delete.

CONFIDENTIAL | © 2020 EPAM Systems, Inc. 86


Delete Stored Procedure. Using Transact-SQL

1. From the File menu, click New Query.


2. Create your own query to delete a proc.

DROP PROCEDURE procedure_name

CONFIDENTIAL | © 2020 EPAM Systems, Inc. 87


Delete Stored Procedure. Using Transact-SQL

1. From the File menu, click New Query.


2. Create your own query to delete a proc.

DROP PROCEDURE procedure_name

IF OBJECT_ID ( '<procedure_name>', 'P' ) IS NOT NULL


DROP PROCEDURE <procedure_name>;
GO

CREATE PROCEDURE <procedure_name>


AS

CONFIDENTIAL | © 2020 EPAM Systems, Inc. 88


Rename Stored Procedure. Using SQL Server Management Studio

1. Expand Databases, expand


the AdventureWorks2019 database, and then
expand Programmability.
2. Expand Stored Procedures, right-click the procedure to
modify, and then click Rename.

CONFIDENTIAL | © 2020 EPAM Systems, Inc. 89


Rename Stored Procedure. Using Transact-SQL

1. From the File menu, click New Query.


2. Create your own query to rename a proc.

--Rename the stored procedure


EXEC sp_rename '<old_name_of_proc>', '<new_name_of_proc>'

CONFIDENTIAL | © 2020 EPAM Systems, Inc. 90


System Stored Procedures

exec sp_help – reports information about a database objects

CONFIDENTIAL | © 2020 EPAM Systems, Inc. 91


Temporary Stored Procedures

Temporary stored procedures are like normal stored procedures but, as


their name suggests, have fleeting existence

There are two kinds of temporary stored procedures:


local(#) and global(##)

CONFIDENTIAL | © 2020 EPAM Systems, Inc. 92


Temporary Stored Procedures. Local Procedure

A local temporary stored procedure is available only in the current session and is dropped
when the session is closed

CREATE PROCEDURE #TempProc


AS
SET NOCOUNT ON
PRINT 'This is a Temporary Proc'

EXEC #TempProc

CONFIDENTIAL | © 2020 EPAM Systems, Inc. 93


Temporary Stored Procedures. Global Procedure

A global temporary stored procedure is visible to all sessions and is dropped when the
session of the user that created it is closed

CREATE PROCEDURE ##TempProc


AS
SET NOCOUNT ON
PRINT 'This is a Temporary Proc'

EXEC ##TempProc

CONFIDENTIAL | © 2020 EPAM Systems, Inc. 94


Temporary Stored Procedures. Local and Global Procedures

They are located under System databases -> Programmability -> Stored Procedures

CONFIDENTIAL | © 2020 EPAM Systems, Inc. 95


System Stored Procedures

exec sp_help – reports information about a database objects

exec sys.sp_tables – reports information about the list of the tables from the
database

exec sp_helptext – is used to create an object in multiple rows

exec sp_depends – is used to get the dependent object details

CONFIDENTIAL | © 2020 EPAM Systems, Inc. 96


Limitations and Disadvantages of Stored Procedures

T E S T I N G O F A L O G I C W H I C H I S E N C A P S U L AT E D
1
I N S I D E A S P I S V E R Y D I F F I C U LT

DEBUGGING STORED PROCEDURES WILL EITHER


2
B E V E R Y D I F F I C U LT

PORTABILITY – IN CASE OF MOVING FROM ONE DATABASE TYPE


3
(ORACLE) TO ANOTHER DATABASE TYPE(MS SQL SERVER)

THE MEMORY USAGE OF EVERY CONNECTION


4
THAT IS USING THOSE SP WILL INCREASE

CONFIDENTIAL | © 2020 EPAM Systems, Inc. 97


SQL user-defined functions

CONFIDENTIAL | © 2020 EPAM Systems, Inc.


Definition of User-Defined Functions

Like functions in programming languages, SQL Server user-defined functions (UDFs) are routines that accept
parameters, perform an action, such as a complex calculation, and return the result of that action as a value
The return value can either be a single scalar value or a result set

CONFIDENTIAL | © 2020 EPAM Systems, Inc. 99


Why use user-defined functions (UDFs)?
THEY ALLOW MODUL AR T H E Y A L LO W FA S T E R THEY CAN REDUCE
PROGRAMMING EXECUTION NETWORK TRAFFIC

• You can create the • Similar to stored • An operation that


function once, store it procedures, Transact- filters data based on
in the database, and SQL user-defined some complex
call it any number of functions reduce the constraint that cannot
times in your program compilation cost of be expressed in a
• User-defined functions Transact-SQL code by single scalar
can be modified caching the plans and expression can be
independently of the reusing them for expressed as a
program source code repeated executions function

CONFIDENTIAL | © 2020 EPAM Systems, Inc. 100


Types of user-defined functions

• Scalar Function • Table-Valued Functions • System Functions

CONFIDENTIAL | © 2020 EPAM Systems, Inc. 101


Types of functions

• Scalar Function • Table-Valued Functions • System Functions

• User-defined scalar functions return • User-defined table-valued functions • SQL Server provides many system
a single data value of the type return a table data type functions that you can use to
defined in the RETURNS clause perform a variety of operations.
They cannot be modified. For more
information, see Built-in Functions
(Transact-SQL), System Stored
Functions (Transact-SQL),
and Dynamic Management Views
and Functions (Transact-SQL)

CONFIDENTIAL | © 2020 EPAM Systems, Inc. 102


Create UDFs. Scalar Functions

Scalar UDFs Create Syntax


CREATE FUNCTION FunctionName
(@Param1 Data_Type_For_Param1)
RETURNS Function_Data_Type
AS
BEGIN
-- Declare the return variable here
DECLARE @ResultVar Function_Data_Type
-- Add the T-SQL statements to compute the
return value here
SELECT @ResultVar = ...
-- Return the result of the function
RETURN @ResultVar

END
GO

CONFIDENTIAL | © 2020 EPAM Systems, Inc. 103


Create UDFs. Scalar Functions

Scalar UDFs Create Syntax


CREATE FUNCTION FunctionName CREATE FUNCTION YtdSales()
(@Param1 Data_Type_For_Param1)
RETURNS Function_Data_Type RETURNS MONEY
AS AS
BEGIN BEGIN
-- Declare the return variable here -- Declare the return variable here
DECLARE @ResultVar Function_Data_Type DECLARE @YtdSales MONEY
-- Add the T-SQL statements to compute -- Add the T-SQL statements to compute
SELECT @ResultVar = ... SELECT @YtdSales = SUM(SalesYTD) FROM
-- Return the result of the function [Sales].[SalesTerritory]
RETURN @ResultVar -- Return the result of the function
RETURN @YtdSales
END END
GO GO

CONFIDENTIAL | © 2020 EPAM Systems, Inc. 104


Create UDFs. Scalar Functions

Scalar UDFs Call Syntax

DECLARE @YtdResults MONEY


SELECT @YtdResults = dbo.YtdSales()
PRINT @YtdResults

CONFIDENTIAL | © 2020 EPAM Systems, Inc. 105


Create UDFs. Table-Valued Functions

Scalar UDFs Create Syntax


CREATE FUNCTION FunctionName
(@Param1 Data_Type_For_Param1)
RETURNS TABLE
AS RETURN
{sql_statement}
GO

CONFIDENTIAL | © 2020 EPAM Systems, Inc. 106


Create UDFs. Table-Valued Functions

Scalar UDFs Create Syntax


CREATE FUNCTION FunctionName
(@Param1 Data_Type_For_Param1)
RETURNS TABLE
AS RETURN
{sql_statement}
GO CREATE FUNCTION St_TabValed(@TerritoryID
INT)
RETURNS TABLE
AS RETURN
SELECT [Name], CountryRegionCode, [Group],
SalesYTD
FROM [Sales].[SalesTerritory]
WHERE TerritoryID = @TerritoryID

CONFIDENTIAL | © 2020 EPAM Systems, Inc. 107


Create UDFs. Table-Valued Functions

Scalar UDFs Call Syntax

SELECT * FROM dbo.St_TabValed(7)


SELECT [Name], [Group] FROM dbo.St_TabValed(7)

CONFIDENTIAL | © 2020 EPAM Systems, Inc. 108


Create UDFs. Table-Valued Functions (multi-statement)

Scalar UDFs Create Syntax


CREATE FUNCTION FunctionName
(@Param1 Data_Type_For_Param1)
RETURNS @Table_Variable_Name TABLE
(Column_1 Data_Type_For_Column1)
AS
BEGIN
{sql_statement}
RETURN
END Take a look at:
GO
FUNCTION [dbo].[ufnGetContactInformation]

CONFIDENTIAL | © 2020 EPAM Systems, Inc. 109


Create UDFs. Aggregate Functions

A user-defined aggregate (UDA) function returns a scalar result that is the result of a calculation
on values in a set of rows

Examples of such functions include built-in SQL Server aggregate functions such as SUM, AVG,
MIN, and MAX.

To create your own you can read Create User-defined Aggregates page on MSDN

https://docs.microsoft.com/en-us/sql/relational-databases/user-defined-functions/create-user-
defined-aggregates?view=sql-server-ver15

CONFIDENTIAL | © 2020 EPAM Systems, Inc. 110


Modify an UDF. Using SQL Server Management Studio

1. Click on the plus sign next to the database that contains the
function you wish to modify.
2. Click on the plus sign next to the Programmability folder.
3. Click the plus sign next to the folder that contains the
function you wish to modify:
1. Table-valued Function
2. Scalar-valued Function
3. Aggregate Function
4. Right-click the function you want to modify and
select Modify.

CONFIDENTIAL | © 2020 EPAM Systems, Inc. 111


Modify an UDF. Using Transact-SQL

1. From the File menu, click New Query.


2. Create your own query to modify a UDF.

ALTER FUNCTION function_name


...

CONFIDENTIAL | © 2020 EPAM Systems, Inc. 112


Delete an UDF. Using SQL Server Management Studio

1. Click on the plus sign next to the database that contains the
function you wish to modify.
2. Click on the plus sign next to the Programmability folder.
3. Click the plus sign next to the folder that contains the
function you wish to modify:
1. Table-valued Function
2. Scalar-valued Function
3. Aggregate Function
4. Right-click the function you want to delete and select Delete.

CONFIDENTIAL | © 2020 EPAM Systems, Inc. 113


Delete an UDF. Using Transact-SQL

1. From the File menu, click New Query.


2. Create your own query to delete an UDF .

-- determines if function exists in database


IF OBJECT_ID (function_name, N'IF') IS NOT NULL
-- deletes function
DROP FUNCTION function_name
GO

CONFIDENTIAL | © 2020 EPAM Systems, Inc. 114


Rename an UDF. Using SQL Server Management Studio

1. In Object Explorer, click the plus sign next to the database


that contains the function you wish to rename and then
2. Click the plus sign next to the Programmability folder.
3. Click the plus sign next to the folder that contains the
function you wish to rename:
1. Table-valued Function
2. Scalar-valued Function
3. Aggregate Function
4. Right-click the function you wish to rename and
select Rename.

CONFIDENTIAL | © 2020 EPAM Systems, Inc. 115


Rename an UDF. Using Transact-SQL

This task cannot be performed using Transact-SQL statements


To rename a user-defined function using Transact-SQL, you must first delete the existing function and then re-create it with the new
name. Ensure that all code and applications that used the function's old name now use the new name

CONFIDENTIAL | © 2020 EPAM Systems, Inc. 116


System Functions

SQL Server has many built-in functions.


This reference contains string, numeric, date, conversion, and some advanced
functions in SQL Server

CONFIDENTIAL | © 2020 EPAM Systems, Inc. 117


Limitations and Disadvantages of UDF in SQL Server

C A N N OT B E U S E D TO P E R F O R M A C T I O NS
1
T H A T M O D I F Y T H E D A TA B A S E S TA T E

C A N N O T C O N TA I N A N O U T P U T I N T O C L A U S E
2
T H AT H A S A TA B L E A S I T S TA R G E T

C A N N O T R E T U R N M U LT I P L E R E S U LT
3 7 S E T S TAT E M E N T S A R E N O T A L L O W E D
SETS

U D F D O E S N O T S U P P O R T T R Y. . . C AT C H ,
4 8 THE FOR XML CLAUSE IS NOT ALLOWED
@ERROR OR RAISERROR

C A N N OT C A L L A S TO R E D
5
PROCEDURE

C A N N OT M A K E U S E O F D Y N A M I C
6
S Q L O R T E M P TA B L E S

CONFIDENTIAL | © 2020 EPAM Systems, Inc. 118


But…

• User-defined functions can be nested; that is, one user-defined function can call another

• The nesting level is incremented when the called function starts execution, and decremented
when the called function finishes execution
• User-defined functions can be nested up to 32 levels. Exceeding the maximum levels of
nesting causes the whole calling function chain to fail

CONFIDENTIAL | © 2020 EPAM Systems, Inc. 119


Stored Proc vs User-Defined Function

User-defined function Stored proc


The function must return a value (single) In Stored Procedure it is optional (can return multiple)

Functions can have only input parameters Procedures can have input or output parameters

Functions can be called from Procedure Procedures cannot be called from a Function

Function allows only SELECT statement The procedure allows SELECT as well as DML
(INSERT/UPDATE/DELETE) statement
Function can be embedded in a SELECT statement Procedures cannot be utilized in a SELECT

Function can be used in the SQL statements anywhere in the Stored Procedures cannot
WHERE/HAVING
Try-Catch block cannot be used in a Function Try-Catch block can be used in a Procedure

Transactions cannot be used Transactions can be used

Cannot use dynamic SQL and temporary tables Dynamic SQL and temporary tables can be used

CONFIDENTIAL | © 2020 EPAM Systems, Inc. 120


SQL TRIGGERS

CONFIDENTIAL | © 2020 EPAM Systems, Inc.


Concept of Triggers
[AdventureWorks2019].[Sales].[SalesOrderDetail]

CONFIDENTIAL | © 2020 EPAM Systems, Inc.


Concept of Triggers
[AdventureWorks2019].[Sales].[SalesOrderDetail]

If there is an order for


$1000, it should be an
automated email being
sent

CONFIDENTIAL | © 2020 EPAM Systems, Inc.


Concept of Triggers
[AdventureWorks2019].[Sales].[SalesOrderDetail]

If there is an order for


$1000, it should be an
automated email being
sent

If there is an order for


$1M, we should rollback it
+ email + log this event in a
table

CONFIDENTIAL | © 2020 EPAM Systems, Inc.


Concept of Triggers
[AdventureWorks2019].[Sales].[SalesOrderDetail]

If there is an order for


$1000, it should be an
automated email being
sent

If there is an order for


$1M, we should rollback it
+ email + log this event in a
table

SQL statements

CONFIDENTIAL | © 2020 EPAM Systems, Inc.


Definition of Trigger

A Trigger is a special kind of procedure that executes in response to certain action on the table like
insertion, deletion or updation of data

It is a database object which is bound to a table and is executed automatically. You can’t explicitly invoke
triggers. The only way to do this is by performing the required action on the table that they are assigned to

CONFIDENTIAL | © 2020 EPAM Systems, Inc. 126


Triggers in SQL Server Management Studio

There are two types of triggers that can be created:

• DML (Data Manipulation Language) triggers and


• DDL (Data Definition Language) triggers

CONFIDENTIAL | © 2020 EPAM Systems, Inc. 127


Triggers in SQL Server Management Studio

There are two types of triggers that can be created:

• DML (Data Manipulation Language) triggers


The DML triggers are those that fire when a SQL statement tries to change the data of a given table or
view. These can be created on tables and views.

• DDL (Data Definition Language) triggers

CONFIDENTIAL | © 2020 EPAM Systems, Inc. 128


Triggers in SQL Server Management Studio

There are two types of triggers that can be created:

• DML (Data Manipulation Language) triggers


The DML triggers are those that fire when a SQL statement tries to change the data of a given table or
view. These can be created on tables and views.

• DDL (Data Definition Language) triggers


On the other hand, DDL triggers fire when a SQL statement tries to change the physical structure of the
database (i.e. create, alter or delete database objects). Additionally, there are DDL triggers that fire when
there are changes to server objects (i.e. create, alter or drop linked servers or databases).

CONFIDENTIAL | © 2020 EPAM Systems, Inc. 129


Triggers in SQL Server Management Studio

There are two types of triggers that can be created:

• DML (Data Manipulation Language) triggers

CONFIDENTIAL | © 2020 EPAM Systems, Inc. 130


Triggers in SQL Server Management Studio

There are two types of triggers that can be created:

• DDL (Data Definition Language) triggers

CONFIDENTIAL | © 2020 EPAM Systems, Inc. 131


Types of DML Triggers

AFTER TRIGGER INSTEAD OF TRIGGER

• AFTER triggers are executed after the action of the INSERT, • INSTEAD OF triggers override the standard actions of the
UPDATE, MERGE, or DELETE statement is performed. triggering statement.

• AFTER triggers are never executed if a constraint violation • Therefore, they can be used to perform error or value
occurs. checking on one or more columns and the perform additional
actions before insert, updating or deleting the row or rows.

• The primary advantage of INSTEAD OF triggers is that they


enable views that would not be updatable to support
updates. For example, a view based on multiple base tables
must use an INSTEAD OF trigger to support inserts, updates,
and deletes that reference data in more than one table.

CONFIDENTIAL | © 2020 EPAM Systems, Inc. 132


Create After Trigger

The CREATE TRIGGER statement allows you to create a new trigger that is fired automatically whenever an event such
as INSERT, DELETE, or UPDATE occurs against a table.

The following illustrates the syntax of the CREATE TRIGGER statement:

CREATE TRIGGER trigger_name


ON table_name
AFTER { INSERT, UPDATE, DELETE }
AS { T-SQL_statement }

GO

CONFIDENTIAL | © 2020 EPAM Systems, Inc. 133


Create After Trigger. Example

For example, we don’t want anybody to insert shifts

CREATE TRIGGER Trg_Shift


ON [HumanResources].[Shift]
AFTER INSERT
AS
BEGIN
PRINT 'INSERT IS NOT ALLOWED!'
ROLLBACK TRANSACTION
END
GO

CONFIDENTIAL | © 2020 EPAM Systems, Inc. 134


Create After Trigger. Example

What is interesting here?

USE AdventureWorks2019
GO

CREATE TRIGGER Sales.uStore


ON Sales.Store
AFTER UPDATE
AS
UPDATE Sales.Store
SET ModifiedDate = GETDATE()
FROM inserted WHERE inserted.BusinessEntityID =
Sales.Store.BusinessEntityID
GO

CONFIDENTIAL | © 2020 EPAM Systems, Inc. 135


“Virtual” tables for triggers: INSERTED and DELETED

SQL Server provides two virtual tables that are available specifically for triggers called INSERTED and DELETED tables.
SQL Server uses these tables to capture the data of the modified row before and after the event occurs.
The following table shows the content of the INSERTED and DELETED tables before and after each event:

DML event INSERTED table DELETED table


holds holds
INSERT rows to be empty
inserted
UPDATE new rows existing rows
modified by the modified by the
update update
DELETE empty rows to be
deleted

CONFIDENTIAL | © 2020 EPAM Systems, Inc. 136


Create Instead Of Trigger

An INSTEAD OF trigger is a trigger that allows you to skip an INSERT, DELETE, or UPDATE statement to a table or a view
and execute other statements defined in the trigger instead. The actual insert, delete, or update operation does not
occur at all.

In other words, an INSTEAD OF trigger skips a DML statement and execute other statements.

CREATE TRIGGER trigger_name


ON table_name
INSTEAD OF { INSERT, UPDATE, DELETE }
AS { T-SQL_statement }

GO

CONFIDENTIAL | © 2020 EPAM Systems, Inc. 137


Create Instead Of Trigger. Example

For example, we don’t want anybody to delete shifts:

CREATE TRIGGER Trg_Shift


ON [HumanResources].[Shift]
INSTEAD OF DELETE
AS
BEGIN
PRINT 'DELETE OF SHIFT IS NOT ALLOWED!'
ROLLBACK TRANSACTION
END
GO

CONFIDENTIAL | © 2020 EPAM Systems, Inc. 138


Modify or Rename DML Triggers

To modify a DML trigger


• You can use ATLER TRIGGER

To rename a DML trigger


1. Delete the trigger that you want to rename
2. Re-create the trigger, specifying the new name

CONFIDENTIAL | © 2020 EPAM Systems, Inc. 139


Modify or Rename DML Triggers

To modify a DML trigger


• You can use ATLER TRIGGER

USE [AdventureWorks2019]
GO

ALTER TRIGGER [Sales].[uStore]


ON [Sales].[Store]
AFTER UPDATE
AS UPDATE Sales.Store SET ModifiedDate =
GETDATE() FROM inserted WHERE
inserted.BusinessEntityID =
Sales.Store.BusinessEntityID
SELECT * FROM deleted
GO

CONFIDENTIAL | © 2020 EPAM Systems, Inc. 140


Modify or Rename DML Triggers

To rename a DML trigger


1. Delete the trigger that you want to rename
2. Re-create the trigger, specifying the new name
IF OBJECT_ID ('Sales.uStore','TR') IS NOT
NULL
DROP TRIGGER Sales.uStore
GO

CREATE TRIGGER [Sales].[trg_Store]


ON [Sales].[Store]
AFTER UPDATE
AS UPDATE Sales.Store SET ModifiedDate =
GETDATE() FROM inserted WHERE
inserted.BusinessEntityID =
Sales.Store.BusinessEntityID
SELECT * FROM deleted
GO
CONFIDENTIAL | © 2020 EPAM Systems, Inc. 141
DDL Triggers

• DDL (Data Definition Language) triggers


On the other hand, DDL triggers fire when a SQL statement tries to change the physical structure of the
database (i.e. create, alter or delete database objects). Additionally, there are DDL triggers that fire when
there are changes to server objects (i.e. create, alter or drop linked servers or databases).

CONFIDENTIAL | © 2020 EPAM Systems, Inc. 142


DDL Triggers

• DDL (Data Definition Language) triggers


On the other hand, DDL triggers fire when a SQL statement tries to change the physical structure of the
database (i.e. create, alter or delete database objects). Additionally, there are DDL triggers that fire when
there are changes to server objects (i.e. create, alter or drop linked servers or databases).

Use DDL triggers when you want to do the following:


• Prevent certain changes to your database schema
• Have something occur in the database in response to a change in your database schema
• Record changes or events in the database schema

CONFIDENTIAL | © 2020 EPAM Systems, Inc. 143


DDL Triggers. CREATE TRIGGER Syntax

CREATE TRIGGER trigger_name


ON {DATABASE | ALL SERVER}
FOR|AFTER {event_type | event_group}
AS {sql_statement}

Examples of event_types:
• CREATE_VIEW
• ALTER_VIEW
• DROP_VIEW
• CREATE_TABLE
• DROP_DATABASE
• …

CONFIDENTIAL | © 2020 EPAM Systems, Inc. 144


DDL Triggers. Example

• DDL (Data Definition Language) triggers


Let’s now deny the creation of new tables

CREATE TRIGGER DB_LEVEL_TRIGGER


ON DATABASE
AFTER CREATE_TABLE
AS
BEGIN
PRINT 'CREATION OF NEW TABLES IS NOT
ALLOWED!'
ROLLBACK TRANSACTION
END

CREATE TABLE MYDEMOTABLE(Col1 int)

CONFIDENTIAL | © 2020 EPAM Systems, Inc. 145


Trigger Limitations

CREATE TRIGGER MUST BE THE FIRST


1 STATEMENT IN THE BATCH AND CAN
APPLY TO ONLY ONE TABLE

A TRIGGER IS CREATED ONLY IN THE


2
CURRENT DATABASE

ALTHOUGH A TRUNCATE TABLE


STATEMENT IS IN EFFECT A DELETE
3
STATEMENT, IT DOESN'T ACTIVATE A
TRIGGER

INSTEAD OF DELETE/UPDATE TRIGGERS


CAN'T BE DEFINED ON A TABLE THAT
4
HAS A FOREIGN KEY WITH A CASCADE
ON DELETE/UPDATE ACTION DEFINED

CONFIDENTIAL | © 2020 EPAM Systems, Inc. 146


T H A N K S F O R YO U R AT T E N T I O N ! Q U E S T I O N S ?

CONFIDENTIAL | © 2020 EPAM Systems, Inc.

You might also like