You are on page 1of 30

Topic 4.

Features of SQL implementation in


MS SQL Server DBMS

HNEU,
Department of Information Systems,
Databases course,
V. V. Fedko
Contents
1. Transact-SQL language
2. Batches
3. Flow control
4. Statement WHILE
5. Cursors
6. Stored procedures
7. User-defined Functions (UDF)
8. Triggers

HNEU, Department of Information Systems, Course Database, V. V. Fedko 2


Test questions
En: Ru:
1. Compare Stored procedures and User- 1. Сравните хранимые процедуры и
defined Functions функции пользователя
2. Using variables, write a script to 2. Используя переменные, запишите
calculate the sum of numbers from 1 to скрипт для вычисления суммы чисел от
20. If you get an amount less than 200, 1 до 20. Если вы получите сумму
print Little, otherwise print Many. меньше 200, выведите Мало, в
противном случае выведите Много.
3. Describe trigger assignment
3. Опишите назначение тригера

Send your answers at email Name the Word file according to the template
fvv.stud@gmail.com TN_Surname_specialty_group, for example,
T4_Johnson_121.017_1.

HNEU, Department of Information Systems, Course Database, V. V. Fedko 3


1. Transact-SQL language
General concepts
Transact-SQL (T-SQL) - procedural extension of the SQL language from
Microsoft (for Microsoft SQL Server).
SQL has been enhanced with such extra features:
• control operators,
• procedures, functions and triggers,
• local and global variables,
• various additional functions for processing strings, dates, mathematics, etc.
Transact-SQL is the key to using SQL Server. All applications that interact with
SQL Server send Transact-SQL statements to the server.

HNEU, Department of Information Systems, Course Database, V. V. Fedko 4


Variables
Variables are intended for temporary storage of data and
their further use in one batch.
A batch is one or more T-SQL commands sent by the client
application to SQL Server for further execution as a whole.
Variables are used in batches and scripts:
• as a cycle counter;
• save the value to be verified by the flow control
instruction (conditional logic);
• store the value returned by a function or stored
procedure.

HNEU, Department of Information Systems, Course Database, V. V. Fedko 5


Variable Commands
DECLARE - description
SET - assignment of value
The scope of a variable is all the instructions between
its declaration and the end of the batch or stored
procedure in which it is declared.

1. One variable 2. Several variables

DECLARE @Quantity AS smallint; DECLARE @Name nvarchar (25), @Price money;


SET @Quantity = 100; SET @Name = N'Bread "Ukrainian"';
SET @Price = 13.50;

HNEU, Department of Information Systems, Course Database, V. V. Fedko 6


3. Expression 4. In Select
DECLARE @Name nvarchar (25); DECLARE @Name nvarchar (25);
SET @Name = SELECT @Name = Name
(SELECT Name FROM Products
FROM Products WHERE ProductId = 2;
WHERE ProductId = 2);
SELECT @Name AS Name; SELECT @Name AS Name;

5. Several rows - last

DECLARE @Name nvarchar (25);


SELECT @Name = Name
FROM Products;
SELECT @Name AS Name;

HNEU, Department of Information Systems, Course Database, V. V. Fedko 7


2. Batches
Definition
A batch is a group of one or more Transact-SQL
statements that are simultaneously sent from
the application to SQL Server for execution.
Transact-SQL statements are separated by semicolons,
and batches are separated using the GO command.

HNEU, Department of Information Systems, Course Database, V. V. Fedko 8


The order of execution of batches
SQL Server compiles the batch instructions into a single executable module called the execution
plan. The instructions in the execution plan are then sequentially executed.
A compilation error, such as a syntax error, stops the compilation of the execution plan.
Therefore, no instructions in the batch are executed.
A runtime error, such as arithmetic overflow or violation of a constraint, leads to one of two
results:
• Most runtime errors stop the current instruction and the instructions following it in the batch.
• Some runtime errors, for example, violation of constraints, stop only the current instruction.
All other instructions in the batch will be executed.
This does not affect instructions that are executed before the instruction in which the execution
error occurred.
The only exception is if the batch is in a transaction and the transaction will be rolled back due
to an error. In this case, any unfixed data changes made before the execution error will be
cancelled.

HNEU, Department of Information Systems, Course Database, V. V. Fedko 9


Batch Rules
• CREATE instructions cannot be combined with other instructions in a
batch.
• In the same batch, you cannot first alter the table and then access the
new columns.
• If the EXECUTE statement is the first instruction in the batch, the
EXECUTE keyword is not required. The EXECUTE keyword is required if
the EXECUTE statement is not the first instruction in the batch.
• EXECUTE ≡ EXEC

HNEU, Department of Information Systems, Course Database, V. V. Fedko 10


Block
Definition: Block is a sequence of T-SQL BEGIN
statements that allows you to execute a
group of statements as one statement. {sql_statement | statement_block}
END
The block starts with BEGIN and ends
with END.

DECLARE @User nvarchar(10);


SET @User = 'Customer';
IF @User = 'Admin'
BEGIN
SELECT * FROM Products;
SELECT * FROM Manufacturers
END
ELSE
BEGIN
SELECT Name, Price FROM Products;
SELECT Name FROM Manufacturers
END;

HNEU, Department of Information Systems, Course Database, V. V. Fedko 11


3. Flow control
Statement IF... ELSE
Imposes conditions on the execution
of a Transact-SQL statement.
The optional ELSE keyword allows you to specify an
alternative statement that is executed when the
Boolean_expression is FALSE or NULL.

IF Boolean_expression
{ sql_statement | statement_block }
[ ELSE
{ sql_statement | statement_block } ]

HNEU, Department of Information Systems, Course Database, V. V. Fedko 12


Example IF... ELSE
DECLARE @User nvarchar(10);

SET @User = 'Admin';


IF @User = 'Admin'
SELECT * FROM Products
ELSE
SELECT Name, Price FROM Products;

SET @User = 'Customer';


IF @User = 'Admin'
SELECT * FROM Products
ELSE
SELECT Name, Price FROM Products;

HNEU, Department of Information Systems, Course Database, V. V. Fedko 13


4. Statement WHILE
WHILE assignment
The WHILE statement is used to set the condition for repeated
execution of an SQL statement or block of statements.
These instructions are called in a loop while the specified
condition is true.

WHILE Boolean_expression
{ sql_statement | statement_block | BREAK | CONTINUE }

BREAK - exit from the nearest WHILE loop. The instructions that follow the END keyword
indicating the end of the loop are called.
CONTINUE - a new cycle step will be set and does not take into account all instructions
after CONTINUE.

HNEU, Department of Information Systems, Course Database, V. V. Fedko 14


Example WHILE
--Fill the Dates table with dates WHILE @CurrentDate <= @EndDate
CREATE TABLE Dates (Sale_date DATE); BEGIN
GO INSERT INTO Dates VALUES (@CurrentDate);
SET @CurrentDate = DateAdd(d, 1,
DECLARE @BeginDate DATE; @CurrentDate)
DECLARE @EndDate DATE; END;

SET @BeginDate = '01/01/2010'; select count(*) AS 'Dates quantity' from Dates;


SET @EndDate = '12/31/2020';

DECLARE @CurrentDate DATE;


SET @CurrentDate = @BeginDate;

HNEU, Department of Information Systems, Course Database, V. V. Fedko 15


5. Cursors
Cursors assignment
DML commands (SELECT, UPDATE, DELETE) work directly with groups
of rows.
To work with each selected row use cursors.
Cursor (current set of records) - a temporary set of rows that can be
iterated sequentially, from first to last.

HNEU, Department of Information Systems, Course Database, V. V. Fedko 16


Cursor operations

Cursor declaration: Opening of cursor:


DECLARE cursor_name CURSOR FOR SELECT_statement OPEN cursor_name

Reading the next row from the cursor:


FETCH cursor_name INTO variable_list FETCH => go and get

The global variable is @@ FETCH_STATUS <> 0 if there are no more rows in the cursor.
If the rowset is not yet finished, then @@ FETCH_STATUS = 0, and the FETCH operator will overwrite the field
values from the current row into variables.

Closing of cursor: Deleting of cursor from memory:


CLOSE cursor_name DEALLOCATE cursor_name

HNEU, Department of Information Systems, Course Database, V. V. Fedko 17


Example CURSOR
-- Accumulation sums OPEN C;
CREATE TABLE Accumulations( FETCH FROM C INTO @Sale_date, @Revenue;
Sale_date DATE, SET @Accumulation = 0;
Revenue money, WHILE @@FETCH_STATUS = 0
Accumulation money); BEGIN
GO SET @Accumulation = @Accumulation +
@Revenue;
DECLARE @Revenue money, @Accumulation money; INSERT INTO Accumulations
DECLARE @Sale_date DATE; VALUES(@Sale_date, @Revenue,
DECLARE C CURSOR FOR @Accumulation);
SELECT Sale_date, FETCH FROM C INTO @Sale_date, @Revenue;
SUM(Products.Price*Sales.Quantity) AS Revenue END;
FROM Sales JOIN Products ON CLOSE C;
Sales.ProductId=Products.ProductId DEALLOCATE C;
GROUP BY Sale_date; SELECT * FROM Accumulations;
Sale_date Revenue
16.09.2020 1000
17.09.2020 2000
18.09.2020 1000
HNEU, Department of Information Systems, Course Database, V. V. Fedko 18
6. Stored procedures
Concept of stored procedure
A SQL Server stored procedure is a group of one or more Transact-SQL
statements.
Saved on the server side for improved performance and consistency
of repetitive tasks.
It is precompiled before being saved as an object in the database.
Every time it is called, the already compiled procedure is used.
Processes input parameters and returns values to the caller as output
parameters.

HNEU, Department of Information Systems, Course Database, V. V. Fedko 19


Advantages of Stored Procedures
• Reduced network traffic between clients and server
• Greater safety
• Permissions at the procedure level
• Hiding operators
• Injection Protection
• Encryption
• Code reuse
• Simpler maintenance (in the app)
• Increase in productivity

HNEU, Department of Information Systems, Course Database, V. V. Fedko 20


Creating Stored Procedures

• Transact-SQL Editor:
New query

-- Cost of products of a given manufacturer


CREATE PROCEDURE Manufacturer_cost
@ManufacturerId int,
@Total_cost money OUTPUT
AS
SELECT @Total_cost=SUM(Price*Quantity)
FROM Sales
JOIN Products ON
Sales.ProductId=Products.ProductId
WHERE Sales.ManufacturerId=@ManufacturerId

HNEU, Department of Information Systems, Course Database, V. V. Fedko 21


Calling a stored procedure
• Transact-SQL Editor:

-- Cost of sales of products of the second manufacturer


DECLARE @Total_cost AS money;
EXEC Manufacturer_cost 2, @Total_cost OUTPUT;
SELECT @Total_cost;

HNEU, Department of Information Systems, Course Database, V. V. Fedko 22


7. User-defined Functions (UDF)
Concept of User-defined Function Syntax
CREATE FUNCTION Name (Parameters)
Unlike a stored procedure, it can have only one
result that can be immediately used in an RETURNS type
expression when calling a function. AS
Limitations: BEGIN
• Unable to change database (only SELECT); Declare statements;
• It has no output parameters - because the Processing code;
result is assigned to the function name.
RETURN value
END;

HNEU, Department of Information Systems, Course Database, V. V. Fedko 23


Creating User-defined Functions
CREATE FUNCTION fManufacturer_cost
(
@ManufacturerId int
)
RETURNS money
AS
BEGIN
DECLARE @Total_cost AS money;
SELECT @Total_cost=SUM(Price*Quantity)
FROM Sales
JOIN Products ON Sales.ProductId=Products.ProductId
WHERE Sales.ManufacturerId=@ManufacturerId
RETURN @Total_cost;
END

HNEU, Department of Information Systems, Course Database, V. V. Fedko 24


Calling a function
IF dbo.fManufacturer_cost(1) > dbo.fManufacturer_cost(2)
PRINT N'The cost of products of the first manufacturer is higher than the second'
ELSE
PRINT N'The cost of products of the second manufacturer is higher than the first';

HNEU, Department of Information Systems, Course Database, V. V. Fedko 25


8. Triggers
Concept of Triggers
Definition: A trigger is a special kind of stored procedure that fires and
runs its code when a certain event occurs (event handler).
SQL Server supports two types of events:
• data modification operations (DML triggers),
• change database structure (DDL triggers).
Triggers can be activated either after (AFTER) completion of the
corresponding events or instead of it (INSTEAD OF).
The trigger is performed automatically when updating, adding or
deleting data.
Each trigger is bound to a specific table.

HNEU, Department of Information Systems, Course Database, V. V. Fedko 26


Deleted and inserted tables

DML triggers use the deleted and inserted logical tables. In


their structure, they are similar to the table on which the
trigger is defined, that is, the table to which the user action
is applied.
Deleted and inserted tables contain old or new row values.
Their rows can be used in the script for any operations.

HNEU, Department of Information Systems, Course Database, V. V. Fedko 27


Trigger creation syntax

CREATE TRIGGER Name


ON table_name
AFTER | INSTEAD OF
[ INSERT ] [ , ] [ UPDATE ] [ , ] [ DELETE ]
AS
BEGIN
Declare statements;
Processing code;
END

HNEU, Department of Information Systems, Course Database, V. V. Fedko 28


Trigger example

CREATE TRIGGER trgSalesSold


ON Sales
AFTER INSERT
AS
BEGIN
INSERT INTO Sales
DECLARE @ProductId AS int;
VALUES ('09/03/2021',1,2,100)
DECLARE @Quantity AS smallint;

SELECT @ProductId =(SELECT ProductId


FROM inserted);

SELECT @Quantity = (SELECT Quantity


FROM inserted);

UPDATE Products
SET Sold = Sold + @Quantity
WHERE ProductId= @ProductId;
END

HNEU, Department of Information Systems, Course Database, V. V. Fedko 29


Test questions
En: Ru:
1. Compare Stored procedures and User- 1. Сравните хранимые процедуры и
defined Functions функции пользователя
2. Using variables, write a script to 2. Используя переменные, запишите
calculate the sum of numbers from 1 to скрипт для вычисления суммы чисел от
20. If you get an amount less than 200, 1 до 20. Если вы получите сумму
print Little, otherwise print Many. меньше 200, выведите Мало, в
противном случае выведите Много.
3. Describe triger assignment
3. Опишите назначение тригера

Send your answers at email Name the Word file according to the template
fvv.stud@gmail.com TN_Surname_specialty_group, for example,
T4_Johnson_121.017_1.

HNEU, Department of Information Systems, Course Database, V. V. Fedko 30

You might also like