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

SQLDEV320A WEEK8-1

Uploaded by

adams.radiy
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
16 views

SQLDEV320A WEEK8-1

Uploaded by

adams.radiy
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 44

Instructor:

SQL Server boB Taylor


Developme [email protected]
nt m
SQLDEV
320 A
Spring
2021 MCA, MCM, MCSM,
Week 8 MCSE, MCSD, MCT,
Data Scientist
REVIEW
• RECAP WEEK7

TODAY
• ASSIGNMENT 7 REVIEW

VIEWS

TRIGGERS

DATABASE FILE ARCHITECTURE

DATABASE TABLE ARCHITECTURE

TRANSACTIONS AND
CONCURRENCY

LOCK OBJECTS

BLOCKING AND DEADLOCKS


A view is a virtual table whose contents are
defined by a query.

Like a table, a view consists of a set of


named columns and rows of data.

Views Unless indexed, a view does not exist as a


stored set of data values in a database.

The rows and columns of data come from


tables referenced in the query defining the
view and are produced dynamically when
the view is referenced.
A view acts as a filter on
the underlying tables
referenced in the view.

Views The query that defines the


view can be from one or
more tables or from other
views in the current or
other databases
Views are generally used to focus, simplify,
and customize the perception each user has
of the database.

Views Views can be used as security mechanisms


by letting users access data through the
view, without granting the users
permissions to directly access the
underlying base tables of the view.

Views can be used to provide a backward


compatible interface to emulate a table that
used to exist but whose schema has
changed.
The SELECT clauses in a view definition cannot
include the following:

An ORDER BY clause, unless there is also a TOP


clause in the select list of the SELECT statement

Important The ORDER BY clause is used only to


determine the rows that are returned by the TOP or

Views OFFSET clause in the view definition. The ORDER BY


clause does not guarantee ordered results when the
view is queried, unless ORDER BY is also specified in
the query itself.

The INTO keyword

The OPTION clause

A reference to a temporary table or a table variable.


An indexed view is a view that has been
materialized. This means the view definition has
a ny ions been computed and the resulting data stored just
M rict like a table.
t
res
You index a view by creating a unique clustered
index on it. Indexed views can dramatically improve
the performance of some types of queries.

Indexed Indexed views work best for queries that aggregate


many rows.

Views They are not well-suited for underlying data sets


that are frequently updated.

Can be automatically substituted without rewriting


code.
1. Verify the SET options are correct for all
existing tables that will be referenced in
Indexed the view.

Views - 2. Verify that the SET options for the


session are set correctly before you

Requiremen create any tables and the view.


3. Verify that the view definition is
ts deterministic.
4. Verify that the base table has the same
owner as the view.
5. Create the view by using the WITH
SCHEMABINDING option.
6. Create the unique clustered index on the
view.
https://docs.microsoft.com/en-us/sql/relational-
databases/views/create-indexed-views?view=sql-server-
ver15
What are Triggers

Trigger Types
• FOR | AFTER trigger

Database
• INSTEAD OF trigger

DMLTriggers
Triggers INSERT, UPDATE or DELETE statement to a table or
view
DDL Triggers
CREATE, ALTER, DROP, GRANT DENY, REVOKE,
UPDATE
What are
triggers
A trigger is a special
kind of stored
procedure that
automatically executes
when a table event
occurs in the database
server.
Enforce Enforce business logic

Enforce Enforce referential data integrity

Why do we Apply Apply changes automatically without user


use Triggers? action

Apply transaction commit and rollback


Apply actions

Track Track changes in the database


What are the cons of using
Triggers?
• Additional logic to monitor and maintain
Why do we • Synchronous actions within the scope of
the transaction
use • Hidden from application logic
• Have global scope
triggers? • Recursive triggers can easily cause errors
• Could have unintended consequences
FOR | AFTER Trigger:

DML trigger

Trigger Fired only when all operations specified


in the triggering SQL statement have
Types executed successfully

Cannot be defined on views

FOR was a pre-2000 syntax.


INSTEAD OF Trigger:

DML trigger
Overrides the standard action of the
Trigger Types triggering statement: an INSERT,
UPDATE or DELETE

Can be used in either tables or views

It can be used to bypass the statement


and execute a whole different
statement, or just help us check and
examine the data before the action is
done.
DML Trigger
Command Syntax

CREATE TRIGGER [ schema_name ]. [trigger_name]


ON
{ table }
[ WITH <dml_trigger_option> [ ,...n ] ]
{ FOR | AFTER } { [ INSERT ] [ , ] [ UPDATE ] [ , ] [ DELETE ]}
AS { sql_statement [ ; ] [ ,...n ] }
DML
CREATE TRIGGER
Trigger [ schema_name . ][trigger_name]
Command ON { table | view } [ WITH
<dml_trigger_option> [ ,...n ] ]
Syntax for { FOR | AFTER | INSTEAD OF }
Views { [ INSERT ] [ , ] [ UPDATE ] [ , ]
[ DELETE ] } [ WITH APPEND ]
[ NOT FOR REPLICATION ]
AS { sql_statement [ ; ] [ ,...n ] |
EXTERNAL NAME <method specifier [ ; ]
>}
Simple Trigger Example:
USE [test]
GO

IF OBJECT_ID('[dbo].[Table1]', 'U') IS NOT NULL


DROP TABLE
[dbo].Table1 GO

-- 1 Create table object


CREATE TABLE Table1 (SRC_ID int IDENTITY, [Description]
NVARCHAR(100));
GO

-- 2 Create Insert trigger


CREATE TRIGGER i_trgTable1 ON Table1
FOR INSERT AS
PRINT
GETDATE();
GO

-- 3 Test trigger
INSERT Table1 ([Description]) VALUES ('Test 1');

-- 4 Show results
SELECT *
FROM Table1
AFTER Trigger Example:
USE
[AdventureWorks2019]
GO

CREATE TRIGGER
trg_OrderDetailNotDiscontinued
AS ON [Sales].
-- Prevent for discontinued
[SalesOrderDetail] AFTER
orders IF UPDATE
INSERT, items
EXISTS (
SELECT 1
FROM Production.Product
JOIN INSERTED p
i i.productid = p.productid
ON
WHERE p.DiscontinuedDate < GETDATE()
)
BEGI
N
RAISERROR('Order Item is discontinued. Transaction
Failed.',16,1);
ROLLBACK TRAN;
INSERTED • Inserted and Deleted virtual tables are
and created for the trigger
• Each trigger has its own Inserted and
DELETED Deleted tables
• For every new set of values in a row,
virtual there's a row in the
tables • Inserted virtual table
• For every old set of values in a row,
there's a row in the Deleted virtual
table
• An update generates an Inserted and
Deleted row for every single update.
More on virt
ual tables
Using INSERTED and DELETED virtual
tables
USE
[test]
GO

IF OBJECT_ID('[dbo].[Table2]', 'U') IS NOT NULL


DROP TABLE [dbo].Table2
GO

CREATE TABLE Table2(Col1 int IDENTITY, Col2 varchar(100),


Col3 int) GO
-- Create Insert trigger
CREATE TRIGGER ON
u_trgTest FOR UPDATE, Table2
INSERT, DELETE AS
SELECT 'inserted', * FROM INSERTED -- Virtual table containing
INSERTED rows
SELECT 'deleted',* FROM DELETED-- Virtual table containing DELETED
rows
GO
-- Test trigger
INSERT INTO Table2 VALUES ('Inserted value',
1); UPDATE Table2 SET Col2 = 'Updated
value'; DELETE FROM Table2 WHERE Col1 = 1;
Using DDL triggers:
Triggered by:
CREATE
ALTER
DROP

CREATE TRIGGER tr_ddlProtectTable ON DATABASE


AFTER DROP_TABLE AS
PRINT 'Tables cannot be dropped'
ROLLBACK TRANSACTION
GO
INSTEAD OF Trigger Example
CREATE TABLE BaseTable (
PrimaryKey int PRIMARY KEY IDENTITY(1,1)
,Color varchar(10) NOT NULL
,Material varchar(10) NOT NULL
,ComputedCol AS (Color + Material)
); GO

--Create a view that contains all columns from the basetable.


CREATE VIEW InsteadView
AS
SELECT PrimaryKey, Color, Material, ComputedCol FROM BaseTable;
GO
--Create an INSTEAD OF INSERT trigger on the view.
CREATE TRIGGER InsteadTrigger ON InsteadView INSTEAD OF INSERT
AS
BEGIN
--Build an INSERT statement ignoring inserted.PrimaryKey and ComputedCol. INSERT INTO
BaseTable
SELECT Color, Material FROM inserted;
END
GO
DELETE a Trigger:
DMLTrigger:

DROP TRIGGER [schema_name.]trigger_name [ ,...n ] [ ; ]

DDLTrigger:

DROP TRIGGER trigger_name [ ,...n ] ON { DATABASE | ALL SERVER } [


; ]

Logon Trigger:

DROP TRIGGER trigger_name [ ,...n ] ON ALL SERVER

1
Databases have Data files
(.mdf
minimum two or .ndf)
operating system Log files
files (.ldf)

SQL Server
File Data files contain data and
objects such as tables, indexes,
Architectur stored procedures, and views.

e
Log files contain the
information that is required to
recover all transactions in the
database.
SQL Server Data File
Architecture
A data file A data page SQL Server All pages Uniform Mixed
(.mdf is 8KB in reads data are stored Extent – extent –
or .ndf) is size pages in in extents owned by a shared by
logically groups of 8 single up to 8
divided in pages, or object objects
pages extents

https://technet.microsoft.com/en-us/library/ms190969(v=sql.105).aspx
SQL Server Data File Architecture
Page Type Contents
Data Data rows with all data except for large
objects
Index Index entries
Text/Image Large objects – text, image, varchar(max)
Global Allocation Map Information on whether extents are allocated
Page Free Space Information on page allocation and free space
Index Allocation Map Info on extents used by a table or index
Bulk Changed Map Info on extents modified since last BACKUP
LOG
Differential Changed Info on extents that have changed since
Map last BACKUPDATABASE
SQL Server Table Architecture
A table is contained in one or more partitions

A partition contains data rows in either a:


• A heap
• A clustered index structure.

Heaps are tables that have no clustered index.

Clustered tables are tables built around a clustered


index.
• Indexed views have the same storage structure as clustered tables.

Non-clustered indexes have a B-tree index structure


similar to the one in clustered indexes.
• The difference is that non-clustered indexes do not affect the order of
the data rows.
• The leaf level contains index rows.
Demo

28
• Dirty reads: These occur while a transaction is updating
a row, and a second transaction reads the row before the
first transaction is committed. If the original update rolls
back, the uncommitted changes will be read by the

Transaction
second transaction, even though they are never
committed to the database.

• Non-repeatable reads: These occur when one


transaction is updating data, and a second is

and reading the same data while the update is in


progress. The data retrieved before the update will
not match data retrieved after the update.

Concurrenc
• Phantom reads: These occur when a transaction
issues two reads, and between the two reads the
underlying data is updated with data being
inserted or deleted. This causes the results of

y: Issues
each query to differ. Rows returned in one query
that do not appear in the other are called
phantom-rows.

• Lost updates: This occurs when two


transactions update a row’ s value,
and the transaction to last update
the “row“ wins.” Thus the first update
is lost.
Isolation While READ COMMITTED is used,
uncommitted data modifications can’t be
read. Shared

Levels
locks are used during a query, and data
READCOMMITTED cannot be modified by other processes
(default) while the query is retrieving thedata.

READUNCOMMITTED This is the least restrictive isolation level, issuing no

An Isolation Level locks on the data selected by the transaction.

controls how and when REPEATABLE READ When enabled, dirty and non-repeatable reads are not
the changes made by allowed. This is achieved by placing
shared locks on all read resources.
one transaction are
visible to other SERIALIZABLE Most restrictive setting. Range locks are placed on the

concurrent transactions data based on the search criteria used


to produce the result set. This ensures that
actions such as insertion of new
rows,modification of values, or deletion of
existing rows that would have been returned
within the original query and search criteria are
not allowed.

SNAPSHOT This isolation level allows you to read a transactionally


consistent version of the data as it
existed at the beginning of a transaction. Data reads do
not block data modifications—
however, the SNAPSHOT session will not detect changes
being made.
Setting Isolation Levels
USE [AdventureWorks2019];
GO

SET TRANSACTION ISOLATION LEVEL SERIALIZABLE; -- identify locks


GO SELECT
resource_associated_entity_id
BEGIN TRAN ,resource_type
SELECT CustomerID, ,request_mode
AccountNumber, ,request_session_id
StoreID FROM
FROM Sales.Customer sys.dm_tran_locks;
WHERE CustomerID BETWEEN 1 AND 10;
COMMIT TRAN
Row Lock (RID)
Locks a single row. Escalates to table lock when
transaction threshold is exceeded.

Key Lock(KEY)
Locks nodes on an index

Page Lock (KEY)


SQL Server Locks a page, or 8 KB. Escalates to extent lock
when transaction threshold is exceeded.
Lock Types Extent Lock (EXT)
Locks eight pages, or 64 KB

Table Lock (TAB)


Locks the entire table

Database Lock (DB)


Locks the entire database. This lock is used
primarily during schema changes.
SQL Server Lock Modes
Lock mode Description
Shared (S) Used for read operations that do not change or update data, such as a
SELECT statement.
Update (U) Used on resources that can be updated. Prevents a common form of
deadlock that occurs when multiple sessions are reading, locking, and
potentially updating resources later.
Exclusive (X) Used for data-modification operations, such as INSERT, UPDATE, or DELETE.
Ensures that multiple updates cannot be made to the same resource at the
same time.
Intent Used to establish a lock hierarchy. The types of intent locks are: intent
shared (IS), intent exclusive (IX), and shared with intent exclusive (SIX).
Schema Used when an operation dependent on the schema of a table is executing.
The types of schema locks are: schema modification (Sch-M) and schema
stability (Sch-S).
Bulk Update Used when bulk copying data into a table and the TABLOCK hint is specified.
(BU)
Key-range Protects the range of rows read by a query when using the serializable
transaction isolation level. Ensures that other transactions cannot insert
rows that would qualify for the queries of the serializable transaction if the
queries were run again.
Standard Reports
Viewing Locks
BEGIN TRAN SELECT request_session_id as sessionid,
resource_type as type,
SELECT ProductID, resource_database_id as dbid,
Name
FROM Production.Product Object_name(resource_associated_entity_id,
WITH (TABLOCKX); resource_database_id),
request_mode as rmode,
ROLLBACK; request_status as rstatus
FROM sys.dm_tran_locks
WHERE resource_type IN ( 'DATABASE',
'OBJECT' );

35
Query Hints
SET TRANSACTION ISOLATION LEVEL READ UNCOMMITTED;

SELECT * FROM Sales.SalesOrderDetail WITH(READUNCOMMITTED);

SELECT * FROM Sales.SalesOrderDetail WITH (NOLOCK);

SELECT *
FROM Sales.SalesOrderDetail sod
WITH (NOLOCK)
JOIN
Sales.SalesOrderHeader soh
ON sod.SalesOrderID =
soh.SalesOrderID
ORDER BY sod.ModifiedDate;
SQL server uses locking and row
versioning to prevent users from
reading uncommitted data and
prevent multiple users from
attempting to change the same
data at the same time.

Application can specify that a


transaction use the row versions to
view data a it existed at the start
Row Versioning of the transaction or query instead
of protecting all read with locks.

Users can control row versioning


implementation by enabling and
disabling database options.

SQL Server takes a copy of the


data before the data is changed
and placed in in tempdb.
Turn on Row Versioning
ALTER DATABASE AdventureWorks2019
SET READ_COMMITTED_SNAPSHOT ON;

ALTER DATABASE AdventureWorks2019


SET ALLOW_SNAPSHOT_ISOLATION ON;

What is the cost of row


versioning?
• Tempdb space
• Increase in I/O
• Increase in CPU
• Increase data rows space
A deadlock occurs when
there is a cyclic
dependency between
Deadlocks two or more threads, or
processes, for some set
of resources within SQL
Server.
Deadlocks
Two SPIDs get blocked by each other. Each SPID, while holding its
own resources, attempts to access a resource that is locked by
the other SPID.
A circular blocking scenario.
BEGIN TRANSACTION BEGIN TRANSACTION;

UPDATE UPDATE Production.ProductCategory


Production.ProductCategory SET Name = 'DeadLock Test 2'
SET Name = 'Blocking1' WHERE ProductCategoryID = 1;
WHERE ProductCategoryID = 1
UPDATE Production.ProductCategory
UPDATE SET Name = 'Blocking2'
Production.ProductCategory WHERE ProductCategoryID = 1;
SET Name = 'DeadLock Test1'
WHERE ProductCategoryID = 1 COMMIT TRANSACTION ;

COMMIT TRANSACTION
Collect Deadlock Information
sp_lock

sp_who2
@@Error returns 1205 SQLProfiler
Locks\Lock:Deadlock
Locks\Lock:Deadlock chain

DBCC trace flag


DBCC TRACEON(-1,1204) -- deadlock information
DBCC TRACEON(-1, 3605) -- redirect DBCC output to error
log

--System Health Extended Event


Deadlock Resolution
Lock Monitor - regularly checks for the presence of deadlocks and kills the
SPID with the least cost.

SET DEADLOCK_PRIORITY LOW;-- preferred deadlock


victim
SET DEADLOCK_PRIORITY NORMAL;-- resets it
Ensure transactions always access resources in the same
chronological order

Serialize access to resources


increase isolation level to REPEATABLE READ or SERIALIZABLE
use locking hints to REPEATABLEREAD, HOLDLOCK and
UPDLOCK
Increase Lock Granuality
update t1 with (TABLOCK)
sp_indexoption ‘table.index’,ALLOWROWLOCKS, true
Acces Access objects in the same
s order

Avoid Avoid user interaction in


transactions
Minimize
Deadlock
Keep Keep transactions short and in
one batch

Use Use a low isolation level


Week 8 Assignment

QUIZ 8 CODING
ASSIGNMENT

You might also like