sql4
sql4
Basics”
Submodule “Advanced Databases and SQL
Querying”
Yaroslav Dobrianskyi
Lead Software Engineer
3 DURATION: 3 HOURS
1. SQL Views
2. SQL Computed Columns.
3. SQL Stored Procedures
4. SQL User Defined Functions (UDF)
5. SQL Triggers
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
• 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.
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
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
GO
• 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
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.
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.
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.
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
• 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 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.
• 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.
• 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.
3. You may need to modify the SELECT statement in the SQL pane
to return the rows to be modified.
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.
• 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
USE AdventureWorks2019;
GO
SELECT OBJECT_DEFINITION (OBJECT_ID('HumanResources.vEmployee')) AS ObjectDefinition;
GO
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
You can rename a view in SQL Server 2019 (15.x) by using SQL Server Management Studio or
Transact-SQL
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
EXEC sp_rename
@objname = 'HumanResources.EmployeeInfo',
@newname = 'EmployeeInfos';
You can delete (drop) views in SQL Server 2019 (15.x) by using SQL Server Management Studio or
Transact-SQL
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
USE AdventureWorks2019 ;
GO
IF OBJECT_ID ('HumanResources.EmployeeInfos', 'V') IS NOT NULL
DROP VIEW HumanResources.EmployeeInfos;
GO
• [AdventureWorks2019].[Person].[Person]
• [AdventureWorks2019].[Person].[Person]
• 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
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.
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.
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
• The following example modifies the column added in the previous example
• 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
((CONVERT([int],CONVERT([char](8),getdate(),(112)))-CONVERT([char](8),[Birthdate],(112)))/(10000))
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
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
• Stronger security – the procedure controls what processes and activities are performed and
protects the underlying database objects
• 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
• User-defined
• Temporary
• System
• 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
• With no parameters
• With one parameter
• With multiple parameters
EXEC procedure_name
EXECUTE PERSON_EMAIL
EXEC PERSON_EMAIL
EXEC PERSON_FN_EMAIL
• 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
• 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'
A local temporary stored procedure is available only in the current session and is dropped
when the session is closed
EXEC #TempProc
A global temporary stored procedure is visible to all sessions and is dropped when the
session of the user that created it is closed
EXEC ##TempProc
They are located under System databases -> Programmability -> Stored Procedures
exec sys.sp_tables – reports information about the list of the tables from the
database
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
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
• 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)
END
GO
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
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.
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.
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
• 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
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
Cannot use dynamic SQL and temporary tables Dynamic SQL and temporary tables can be used
SQL statements
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
• 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 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.
GO
USE AdventureWorks2019
GO
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:
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.
GO
USE [AdventureWorks2019]
GO
Examples of event_types:
• CREATE_VIEW
• ALTER_VIEW
• DROP_VIEW
• CREATE_TABLE
• DROP_DATABASE
• …