0% found this document useful (0 votes)
36 views34 pages

T - SQL Course Content

Uploaded by

suresh p
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
36 views34 pages

T - SQL Course Content

Uploaded by

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

T- SQL COURSE

T-SQL, or Transact-SQL, is the proprietary language used to interact with Microsoft SQL Server
databases. It's a powerful tool that combines the declarative nature of SQL with procedural
programming elements, allowing you to perform a wide range of tasks, from simple data retrieval to
complex database administration.

Key Components of T-SQL:

1.Data Definition Language (DDL):

Data Definition Language (DDL) statements defines objects in a database.

Use DDL statements to create, alter, or drop objects in a database

CREATE - statement used to start create new objects like: database, table, view, index, temporary
table, trigger, function or procedure.

ALTER - statement used to modify table name or table columns(add, drop, rename), view, trigger.

DROP - uses to drop objects in the database.

RENAME - uses to change the objects name in the database.

DISABLE TRIGGER - sets status trigger inactive.

ENABLE TRIGGER - sets status trigger active.

COLLATIONS - defines a collation of a database or table column.

UPDATE STATISTICS - updates query optimization statistics on a table or indexed view.

TRUNCATE TABLE - delete all rows from a table

2.DML (Data Manipulation Language)

Data Manipulation Language (DML) affect the information stored in the database.

Use DML statements to insert, update, and delete the rows in the database.

INSERT - insert records into a table.

UPDATE - change records in a table.

DELETE - delete records into a table.

MERGE - insert, update, or delete records on a table from the results of a join.

BULK INSERT - imports records from a data file into a database table or view

Data Control Language (DCL) - permissions statements control which users and logins can access
data and perform operations.

The T-SQL DCL statements are: GRANT, REVOKE, DENY.

GRANT - statement used to grant privileges, roles or permissions on database objects.


REVOKE - uses to revokes permissions granted.

DENY - uses to deny permissions.

TCL (Transaction Control Language)

Transaction Control Language (TCL) commands are used to manage transactions in the database.

The T-SQL TCL statements are: COMMIT, ROLLBACK, SAVEPOINT.

BEGIN DISTRIBUTED TRANSACTION - begin distributed transaction.

BEGIN TRANSACTION - begin transaction statement.

COMMIT TRANSACTION - commit transaction is the end point of a successful transaction.

COMMIT WORK - marks the end of a transaction.

ROLLBACK TRANSACTION - rolls back an unsuccessful transaction.

ROLLBACK WORK - rolls back a user-specified transaction.

SAVE TRANSACTION - sets a savepoint within a transaction


T -SQL Aggregate Functions

AVG - returns the average value.

COUNT - returns the number of rows.

MAX - returns the maximum value.

MIN - returns the minimum value.

SUM - returns the sum of all values.

T- SQL String Functions

Charindex - returns the start position.

Concat - returns a string as a result of a concatenation.

Concat_ws - concatenate two or more strings into a single string.

Left - returns the left part of a character string.

Len - returns the number of characters from a string expression, excluding trailing spaces.

Lower - returns a lowercase character expression.

Ltrim - returns a character expression after it removes leading blanks.

Substring - returns part of a character.

Patindex - returns the starting position of the first occurrence of a pattern in a specified expression.

Replace - replace values of a specified string with another string values.

Right - returns the right part of a character string.

Rtrim - returns a character string after truncating all trailing spaces.

STRING_SPLIT - is a table-valued function to split a string into rows of substrings.

STRING_ESCAPE - is used to escape special characters within a string.

Upper - returns a uppercase character expression.

T SQL Date and Time Data Types and Functions

@@DATEFIRST - returns the first day of each week.

CURRENT_TIMESTAMP - returns the current database system timestamp.

DATEADD - returns a date with the specified number interval added.

DATEDIFF - returns the difference between the specified startdate and enddate.

DATEFROMPARTS - returns a date value for the specified year, month or day.

DATENAME - returns a string that represents the specified datepart of the specified date.

DATEPART - returns an integer that represents the specified datepart of the specified date.
DATETIMEFROMPARTS - returns a datetime value for the specified date and time arguments.

DATETIME2FROMPARTS - returns a datetime2 value for the specified date and time arguments.

DAY - returns from a date an integer that represents the day of the month.

EOMONTH - returns the last day of the month.

GETDATE() - returns the current database system timestamp.

GETUTCDATE() - returns the current database system timestamp.

ISDATE - returns 1 for valid date, time, or datetime value. otherwise, 0.

MONTH - returns an int value that represents the month of the specified date.

SMALLDATETIMEFROMPARTS - returns a smalldatetime value for the specified date and time.

SWITCHOFFSET - returns a datetimeoffset value that is changed from the stored time zone offset.

SYSDATETIME - returns a datetime2(7) value that contains the date and time of the computer on
which the instance of SQL Server is running.

SYSDATETIMEOFFSET - Returns a datetimeoffset(7) value that contains the date and time of the
computer on which the instance of SQL Server is running.

SYSUTCDATETIME - the date and time is returned as UTC time (Coordinated Universal Time).

TIMEFROMPARTS - returns a time value for the specified time and with the specified precision.

TODATETIMEOFFSET - returns a datetimeoffset value that is translated from a datetime2 expression.

YEAR - returns an int value that represents the year of the specified date

T SQL System Functions

@@CONNECTIONS - returns the number of attempted connections.

@@ERROR - returns the error number for the last Transact-SQL statement executed.

@@IDENTITY - returns the last inserted identity value.

@@ROWCOUNT - returns the number of rows affected by the last statement.

ERROR_LINE - returns the line number of occurrence of an error.

ERROR_MESSAGE - returns the message text of the error.

ERROR_NUMBER - returns the error number of the error.

ERROR_PROCEDURE - returns the name of the stored procedure or trigger where an error occurs.

ERROR_SEVERITY - returns the severity value of the error where an error occurs.

ERROR_STATE - returns the state number of the error that caused.

HOST_ID - returns the workstation identification number.

HOST_NAME - returns the workstation name.


ISNULL - replaces NULL with the specified replacement value.

ISNUMERIC - determines whether an expression is a valid numeric type

T SQL Security Functions

CURRENT_USER - returns the name of the current user.

ORIGINAL_LOGIN - returns the name of the login that connected to the instance of SQL Server.

SESSION_USER - returns the user name of the current session in the current database.

SUSER_SID - returns the security identification number (SID).

SYSTEM_USER - returns the system login user name.

USER_NAME - returns a database user name from a specified identification number.

T SQL Metadata Functions

APP_NAME - returns the application name for the current session.

DB_ID - returns the database id number.

DB_NAME - returns the database name.

OBJECT_DEFINITION - returns the definition of a specified object.

OBJECT_ID - returns the database object id number.

OBJECT_NAME - returns the database object name.

OBJECT_SCHEMA_NAME - returns the database schema name.

SCHEMA_ID - returns the schema ID associated with a schema name.

SCHEMA_NAME - returns the schema name associated with a schema ID

T SQL Configuration Functions

@@LOCK_TIMEOUT - returns the current lock time-out setting in milliseconds for the current
session.

@@MAX_CONNECTIONS - returns the maximum number of simultaneous user connections allowed


on an instance of SQL Server.

@@SERVERNAME - returns the name of the local server.

@@SERVICENAME - returns the name of the registry key under which SQL Server is running.

@@SPID - returns the session ID of the current user process.

T SQL Conversion Functions

CAST - convert an expression of one data type to another.

CONVERT - convert an expression of one data type to another.

PARSE - returns the result of an expression, translated to the requested data type in SQL Server.

TRY_CAST - returns a value cast to the specified data type if the cast succeeds.
TRY_CONVERT - returns a value cast to the specified data type if the cast succeeds.

TRY_PARSE - is used for converting expressions from string to date/time and number types.

T SQL Analytic functions

CUME_DIST - calculates the cumulative distribution of a value within a group of values.

FIRST_VALUE - returns the first value from a specified column.

LAST_VALUE - returns the last value from a specified column.

LAG - returns values from a previous row.

LEAD - returns values from a next row.

PERCENT_RANK - is similar to the CUME_DIST function.

PERCENTILE_CONT - calculates a percentile based on a continuous distribution of the column value.

PERCENTILE_DISC - calculates a specific percentile for sorted values in an entire rowset.

T SQL Ranking functions

ROW_NUMBER - its primary purpose is to serialize the rows of the result set in the partitioned order
provided by the OVER clause.

RANK - returns the rank of a value in a given list. The rank of a value is its position in the list, with the
first value having a rank of 1.

DENSE_RANK - returns relative position of rows within a result set.

NTILE - divide the rows in groups.

T- SQL OPERATORS

SQL Server supports several types of operators that can be used to filter or manipulate data in a
database:

Relational operators: These operators are used to compare values in a database and return a
Boolean value (true or false) based on the outcome of the comparison. Examples of relational
operators include = (equal to), > (greater than), and <> (not equal to).

Compound operators: These operators combine multiple conditions to filter data in a database. The
most common compound operator is the AND operator, which returns only rows that meet both
conditions. The OR operator returns rows that meet either condition.

Logical operators: These operators are used to test the truth of a statement or expression. The most
common logical operators are NOT, AND, and OR. NOT negates the value of the statement or
expression, AND returns true if both statements are true, and OR returns true if either statement is
true.

Other operators: include IS NULL, IN, BETWEEN, LIKE, EXISTS, CROSS APPLY, EXCEPT, INTERSECT, etc.

Arithmetic Operators - add, subtract, multiply, divide.

Bitwise Operators - and, or, exclusive or.


Comparison Operators - equal, greater than, less than, not equal.

Compound Operators - add equals, subtract equals, multiply equals.

Logical Operators - all, and, any, between, exists, in, like, not, or, some.

T- SQL DATA TYPES

The Transact SQL language allow you to use various data types like: Numeric (int, numeric, decimal,
float), Character Strings (char, varchar), Unicode Character Strings (nchar, nvarchar) , Date (date,
datetime, datetime2, time) and other data types.

Binary Strings

Binary - fixed length binary data.

Varbinary - variable length binary data.

Image - store binary large object (BLOB).

Character Strings

Char - fixed size string data.

Varchar - variable size string data.

Text - store large amounts of text data.

Date and Time

Date - defines a date in SQL Server.

Datetime - defines a date with a time of day.

Datetime2 - extension of datetime type that has a larger date range.

Datetimeoffset - defines a date with a time of a day that has time zone awareness.

Smalldatetime - defines a date that is combined with a time of day.

Time - defines a time of a day.

Numerics

Bigint - defines an integer data type with 8 bytes storage.

Int - the primary integer data type in SQL Server, has 4 bytes storage.

Smallint - defines an integer data type with 2 bytes storage.

Tinyint - defines an integer data type with 1 byte storage.

Decimal - defines a numeric data type with fixed precision and scale numbers.

Numeric - is functionally identical to decimal.

Bit - an integer data type that can take a value of 1, 0, or NULL.

Float - defines approximate numeric values.


Real - defines approximate numeric values with 4 bytes storage.

Money - represent monetary values.

Unicode Character Strings

Nchar - fixed size unicode string data.

Nvarchar - variable size unicode string data.

NText - store data such as text documents.

Other Data Types

Rowversion - exposes automatically generated, unique binary numbers.

Uniqueidentifier - is considered a character type for the purposes of conversion.

Table - store a result set for processing at a later time.

Cursor - defines an cursor data type for variables or stored procedure OUTPUT parameters.

SQL_VARIANT - stores values of various SQL Server.

XML - defines an xml data type.

T-SQL Select Query

One of the most important features of SQL Server is its ability to execute queries and subqueries to
retrieve data from the database. In this article, we will discuss SQL Server queries and subqueries in
detail.

A SQL Select Query is used to return records from the SQL Server database. Using select queries you
can populate variables, cursors, tables, views.

Queries

A query in SQL Server is a request for data from one or more tables or views in the database. SQL
Server uses the Structured Query Language (SQL) to execute queries. SQL Server queries can be
simple or complex, depending on the requirements of the user. A simple query can retrieve data
from a single table, while a complex query can retrieve data from multiple tables and perform
advanced operations such as sorting, filtering, and grouping.

GROUP BY

The T-SQL GROUP BY is used when an aggregate function exists in the select query.

EX: SELECT r.course_id, SUM(c.price) AS CourseSUM

FROM courses c, register_course r


WHERE c.id=r.course_id

GROUP BY r.course_id

HAVING

The T-SQL HAVING specifies a search condition for a group or an aggregate function.

EX: SELECT r.course_id, SUM(c.price) AS CourseSUM

FROM courses c, register_course r

WHERE c.id=r.course_id

GROUP BY r.course_id

HAVING SUM(c.price) > 70;

ORDER BY

The T-SQL ORDER BY sort rows returned in an select query.

EX:SELECT r.course_id, SUM(c.price) AS CourseSUM

FROM courses c, register_course r

WHERE c.id=r.course_id

GROUP BY r.course_id

HAVING SUM(c.price) > 70

ORDER BY SUM(c.price), r.course_id;

WHERE

The T-SQL WHERE specifies a search condition for the rows returned by the select query.

SELECT * FROM courses c WHERE c.price > 50;

BETWEEN

The T-SQL BETWEEN returns rows if the value is within the range of comparisons.

SELECT * FROM courses WHERE price BETWEEN 50 AND 80;

LIKE

The T-SQL LIKE returns rows if a character string matches a pattern

SELECT * FROM courses c WHERE name LIKE '%Engineering%';

SELECT * FROM courses c WHERE name LIKE 'Eng%';

SELECT * FROM courses c WHERE name LIKE '%ring';

Subqueries
A subquery in SQL Server is a query that is nested inside another query. The subquery can be used to
retrieve data that will be used as input for the outer query. The outer query can be a SELECT,
UPDATE, or DELETE statement. Subqueries are useful when you need to retrieve data from multiple
tables and combine the results into a single result set. Subqueries can also be used to perform
calculations or aggregate functions on data before it is used in the outer query.

EXISTS

The T-SQL EXISTS return rows if a SQL subquery contains any rows.

SELECT * FROM courses c

WHERE EXISTS (SELECT 1 FROM register_course r WHERE c.id=r.course_id);

IN

The T-SQL IN returns rows if a specified value matches any value in a SQL subquery.

SELECT * FROM courses c

WHERE c.id IN (SELECT r.course_id FROM register_course r);

SOME

The T-SQL SOME compares a value with a single column set of values.

SELECT * FROM courses c

WHERE c.id = SOME (SELECT r.course_id FROM register_course r);

ANY

The T-SQL ANY returns rows if any value is equal to one value in a subquery.

SELECT * FROM courses c

WHERE c.id = ANY (SELECT r.course_id FROM register_course r);

SQL Server queries and subqueries are powerful tools for retrieving data from a database. SQL Server
subqueries can be used to retrieve data from multiple tables and perform advanced operations on
the data before it is used in the outer query. By mastering SQL Server queries and subqueries, you
can become an expert in data analysis and reporting

T-SQL Table Joins

This article provides an introduction to what T-SQL joins are and how to use them in the SQL Server
database.

T-SQL Joins are used to return records from two or more tables in a SQL Server database.

A SQL join consists of a query that uses multiple tables. SQL Server query uses clauses, subqueries,
expressions, operators and CTEs.

Inner Join
The T-SQL Inner Join returns rows from two tables when a match is found.

SELECT a.column1, b.column1, b.column2

FROM table_A a, table_B b

WHERE a.column1 = b.column1

AND b.column2 > 100 ;

Left Join

The T-SQL Left Join returns all rows from the left table, even if there are no matches with the right
table.

SELECT a.column1, a.column2, b.column1, b.column2

FROM table_A a LEFT JOIN table_B b

ON a.column1 = b.column1

ORDER BY a.column1;

Right Join

The T-SQL Right Join returns all rows from the right table, even if there are no matches with the left
table.

SELECT a.column1, b.column1, b.column2

FROM table_A a RIGHT JOIN table_B b

ON a.column1 = b.column1

ORDER BY a.column1;

Self Join

The T-SQL Self Join is used to join a table to itself.

SELECT a.column1, b.column1, b.column2

FROM table_A a, table_A b

ON a.column1 = b.column1

ORDER BY a.column1;

T-SQL Table Joins

This article provides an introduction to what T-SQL joins are and how to use them in the SQL Server
database.
T-SQL Joins are used to return records from two or more tables in a SQL Server database.

A SQL join consists of a query that uses multiple tables. SQL Server query uses clauses, subqueries,
expressions, operators and CTEs.

Inner Join

The T-SQL Inner Join returns rows from two tables when a match is found.

SELECT a.column1, b.column1, b.column2

FROM table_A a, table_B b

WHERE a.column1 = b.column1

AND b.column2 > 100 ;

Left Join

The T-SQL Left Join returns all rows from the left table, even if there are no matches with the right
table.

SELECT a.column1, a.column2, b.column1, b.column2

FROM table_A a LEFT JOIN table_B b

ON a.column1 = b.column1

ORDER BY a.column1;

Right Join

The T-SQL Right Join returns all rows from the right table, even if there are no matches with the left
table.

SELECT a.column1, b.column1, b.column2

FROM table_A a RIGHT JOIN table_B b

ON a.column1 = b.column1

ORDER BY a.column1;

Self Join

The T-SQL Self Join is used to join a table to itself.

SELECT a.column1, b.column1, b.column2

FROM table_A a, table_A b

ON a.column1 = b.column1

ORDER BY a.column1;

Cross Join

The T-SQL Cross Join, also known as a Cartesian product, returns the combination of every row from
the first table with every row from the second table. It is used to combine every row from one table
with every row from another table, resulting in a much larger table with a number of rows equal to
the product of the number of rows in each table.

SELECT *

FROM table_A

CROSS JOIN table_B;

T-SQL Control-of-Flow

This article describes how to use the T-SQL Control-of-Flow in SQL Server database. To control the
order of execution in SQL Server in sequential order, it has several control of flow keywords. These
keywords are known as Control-of-flow language. Following are the 10 main SQL Server Control-of-
flow keywords: BEGIN...END, BREAK, CONTINUE, GOTO label, IF...ELSE, RETURN, THROW, TRY...CATCH,
WAITFOR, WHILE.

1. BEGIN...END

The control-of-flow BEGIN...END keyword groups Transact SQL statements in a block to execute.

The syntax for BEGIN...END

BEGIN

{ sql_statement | statement_block }

END

2. BREAK

Use BREAK keyword as an exit statement. If BREAK is inserted into an WHILE loop, once the BREAK
statement is executed, it exits the current loop and executes the further statements.

The syntax for BREAK

BREAK

Example

In the following example, we will show how to use the BREAK keyword to exit a WHILE statement.
First, declare and set the variable @num = 1. This variable is incremented by the value 1 as long as
the WHILE statement is run. To exit the WHILE statement, I set the condition that @num > 2. When
running the script, the Example for SQL Server message will be displayed twice.

3. CONTINUE

The main functionality of CONTINUE is to restart a WHILE LOOP by ignoring the statements after the
CONTINUE keyword.

The syntax for CONTINUE

CONTINUE

Example

The example below shows how to use the CONTINUE keyword to continue running a WHILE
statement. The WHILE statement is set to run from 0 to 4, with the help of the @num variable that is
incremented by 1 as long as the conditions in the WHILE block are met. If the variable @num will
have the value 3, then exit WHILE using BREAK, otherwise, using the CONTINUE keyword, WHILE will
continue running. At the end of WHILE's run, the message Example of T-SQL loops will be displayed
three times.

4. GOTO label

GOTO in SQL Server defines a label and it allows the code to jump onto that label from one section to
another.

The syntax for GOTO

Define the label:

label:

Alter the execution:

GOTO label

Example

The example below shows how to use the GOTO statement in SQL Server. In the BEGIN...END block I
declared two labels Test_1 and Test_2 that represent some access points if the given conditions are
met. After reaching the first point labeled Test_1, go directly to the point labeled Test_3, skipping the
point labeled Test_2

5. IF...ELSE

IF-ELSE control flow statement executes a set of blocks in a way that if the condition mentioned in
the IF parameter is True, the IF block executes, if it is False, then the ELSE block is executed.

The syntax for IF...ELSE

IF Boolean_expression

{ sql_statement | statement_block }

This article describes how to use the T-SQL Control-of-Flow in SQL Server database. To control the
order of execution in SQL Server in sequential order, it has several control of flow keywords. These
keywords are known as Control-of-flow language. Following are the 10 main SQL Server Control-of-
flow keywords: BEGIN...END, BREAK, CONTINUE, GOTO label, IF...ELSE, RETURN, THROW, TRY...CATCH,
WAITFOR, WHILE.

1. BEGIN...END

The control-of-flow BEGIN...END keyword groups Transact SQL statements in a block to execute.

The syntax for BEGIN...END


BEGIN

{ sql_statement | statement_block }

END

2. BREAK

Use BREAK keyword as an exit statement. If BREAK is inserted into an WHILE loop, once the BREAK
statement is executed, it exits the current loop and executes the further statements.

The syntax for BREAK

BREAK

Example

In the following example, we will show how to use the BREAK keyword to exit a WHILE statement.
First, declare and set the variable @num = 1. This variable is incremented by the value 1 as long as
the WHILE statement is run. To exit the WHILE statement, I set the condition that @num > 2. When
running the script, the Example for SQL Server message will be displayed twice.

3. CONTINUE

The main functionality of CONTINUE is to restart a WHILE LOOP by ignoring the statements after the
CONTINUE keyword.

The syntax for CONTINUE

CONTINUE

Example

The example below shows how to use the CONTINUE keyword to continue running a WHILE
statement. The WHILE statement is set to run from 0 to 4, with the help of the @num variable that is
incremented by 1 as long as the conditions in the WHILE block are met. If the variable @num will
have the value 3, then exit WHILE using BREAK, otherwise, using the CONTINUE keyword, WHILE will
continue running. At the end of WHILE's run, the message Example of T-SQL loops will be displayed
three times.

USE model

GO

DECLARE @num int


SET @num = 0

WHILE @num < 5

BEGIN

PRINT 'Example of T-SQL loops'

SET @num = @num + 1

IF @num = 3

BREAK

ELSE

CONTINUE

END;

GO

4. GOTO label

GOTO in SQL Server defines a label and it allows the code to jump onto that label from one section to
another.

The syntax for GOTO

Define the label:

label:

Alter the execution:

GOTO label

Example

The example below shows how to use the GOTO statement in SQL Server. In the BEGIN...END block I
declared two labels Test_1 and Test_2 that represent some access points if the given conditions are
met. After reaching the first point labeled Test_1, go directly to the point labeled Test_3, skipping the
point labeled Test_2.

5. IF...ELSE

IF-ELSE control flow statement executes a set of blocks in a way that if the condition mentioned in
the IF parameter is True, the IF block executes, if it is False, then the ELSE block is executed.

The syntax for IF...ELSE

IF Boolean_expression
{ sql_statement | statement_block }

[ ELSE

{ sql_statement | statement_block } ]

Example

The IF EXISTS condition checks if the select returns a record and if yes then displays YES, otherwise
displays NO.

6. RETURN

RETURN keyword exits the query or procedure unconditionally. It can also be used as an exit
statement as statements after RETURN are not executed further.

The syntax for RETURN

RETURN [ integer_expression ]

Example

In the example below we have two inserts in the students table, between these two inserts is the T-
SQL RETURN statement. The first insert will be inserted in the students table so that the RETURN
statement ends the running of the BEGIN...END block. If we comment the SQL Server RETURN
statement, then both rows will be inserted in the students table

7. THROW

THROW raise an exception and if a CATCH block is available, it allows the CATCH block to execute
further.

The syntax for THROW

THROW

Example

In the following example, we will show how to use the THROW statement to handle possible errors
that may occur in a SQL Server block. The first step is to create a table with a single column that
contains the primary key constraint. The second step is to write the BEGIN TRY...END TRY block that
contains the inserts in the created table, the first two inserts are unique, the third is a duplicate
insert, and the last insert is unique. The third step, the BEGIN CATCH...END CATCH block catches and
displays the error generated by the duplicate insert. The last step is to run the script that will produce
the following result: the first two lines will be inserted, then the error Error in try catch block will be
displayed

8. TRY...CATCH

TRY...CATCH block is used for error handling in T-SQL. If an error is encountered in the TRY block, the
control is given to the CATCH block to handle the error.

The syntax for TRY...CATCH


BEGIN TRY

{ sql_statement | statement_block }

END TRY

BEGIN CATCH

[ { sql_statement | statement_block } ]

END CATCH;

Example

The example below shows how to use the TRY...CATCH to handle errors in SQL Server. The select
written in the BEGIN TRY...END TRY block generates the error, and with the help of the BEGIN
CATCH...END CATCH block the error is caught. The error number is extracted and set in the declared
variable @ErrorNumber. It is also useful to extract the error message that we set in the
@ErrorMessage variable. To extract the error number and message, I used the SQL Server system
functions ERROR_NUMBER and ERROR_MESSAGE.

9. WAITFOR

The execution of statements is paused for a specific time or interval if the WAITFOR keyword is
stated.

The syntax for WAITFOR

WAITFOR

DELAY 'time_to_pass'

| TIME 'time_to_execute'

| [ ( receive_statement ) | ( get_conversation_group_statement ) ]

[ , TIMEOUT timeout ]

Example

In the following example, we will use WAITFOR TIME to insert a new record in the students table at a
time specified by the user. The example also contains WAITFOR DELAY to delay the second insert in
the students table. WAITFOR statement can also be used to execute functions or procedures at a
given time

10. WHILE

The statements mentioned in the WHILE block are executed only if the condition mentioned in the
WHILE parameter turns True. If it is False, the WHILE block doesn't execute further

The syntax for WHILE

WHILE Boolean_expression
{ sql_statement | statement_block | BREAK | CONTINUE }

Example

The example uses an @count variable initially set with the value 1. Then it runs the WHILE statement
as long as the value in @count is less than or equal to 5. Inside the BEGIN...END block, the @count
variable is incremented by the value 1 to avoid the infinite running of the WHILE statement. When
@count becomes greater than 5, the WHILE statement stops. When running the script, the While in
SQL Server message will be displayed five times.

T-SQL Stored Procedures

T-SQL stored procedures are objects created in the SQL Server database and consist of SQL
statements. Stored procedures remain saved in the SQL Server database for calling or executed
whenever needed.

T-SQL stored procedures are mostly used because they can be reused to save time

The advantages of Using Stored Procedures

Reduce network traffic between the server and client.

Improved security for database objects. Controls what database activities are performed.

Reuse of code to save time. Database operations can be encapsulated in procedures.

Easier maintenance. Changes are made only in the stored procedures.

Improved performance. The first time the procedure is executed it compiles and creates an execution
plan which is reused for subsequent executions so that the processing of the procedure takes less
time.

Types of Stored Procedures

User-defined is a procedure created by user in database.

Temporary - these are user-defined procedures and are stored in tempdb.

System - system procedures are included with SQL Server.

Create Procedure

The T-SQL statement Create Procedure is used to create stored procedures.

CREATE PROCEDURE procedure_name

AS

SQL statement

GO;

Alter Procedure
The T-SQL statement Alter Procedure is used to modifies stored procedures.

ALTER PROCEDURE procedure_name

AS

SQL statement

GO;

Create Function

The T-SQL statement Create Function is used to create a user-defined function.

CREATE FUNCTION function_name

RETURNS data_type AS

BEGIN

SQL statement

RETURN value

END;

GO;

Call Stored Procedures

The T-SQL command EXECUTE is used to execute the stored procedures.

EXEC | EXECUTE procedure_name

GO;

Drop Stored Procedures

The T-SQL command DROP PROCEDURE is used to drop or delete the stored procedures.

DROP PROCEDURE procedure_name

GO;

Rename Stored Procedures

The T-SQL command sp_rename is used to rename the stored procedures.

sp_rename 'old_procedure_name', 'new_procedure_name'

GO;

Stored Procedures in Object Catalog Views

To check a procedure uses T-SQL Object Catalog Views.

select * from sys.procedures;


select * from sys.objects where type_desc='SQL_STORED_PROCEDURE';

System Stored Procedures

SQL Server System Stored Procedures are predefined procedures that are included in the SQL Server
database management system. These procedures are stored in the master database and are used for
performing various administrative tasks, such as configuring server settings, managing database
objects, and monitoring server performance.

System Stored Procedures are designed to be executed by system administrators or database


developers with appropriate permissions. They are also useful for automation tasks, as they can be
executed automatically using SQL Server Agent or other scheduling tools. SQL Server database allow
you to use various system stored procedures like: sp_tables, sp_table_privileges,
sp_stored_procedures, sp_cursor, sp_executesql, sp_rename, sp_lock, sp_help.

Some of the most commonly used System Stored Procedures in SQL Server include:

stored Procedures - Defining a Stored Procedure | Essential SQL

Sp_addextendedproperty - Adds a new extended property to a database object.

Sp_autostats - Displays or changes the automatic statistics update option.

Sp_columns - Returns column information for the specified database objects.

Sp_column_privileges - Returns column privilege information for a table.

Sp_special_columns - Returns the optimal set of columns that uniquely identify a row in the table.

Sp_configure - Displays or changes global configuration settings for the current server.

Sp_databases - Shows all databases name and size for an instance of the SQL Server.

Sp_execute - Executes a prepared Transact-SQL statement using a specified handle and optional
parameter value.

Sp_executesql - Executes a Transact-SQL statement that can be reused many times.

Sp_fkeys - Returns foreign key informations.

Sp_help - List informations about a database objects.

Sp_helpconstraint - Returns a list of all constraint types.

Sp_helpdb - List informations about databases.

Sp_helpindex - Returns information about the indexes on a table or view.

Sp_lock - Shows information about locks.

Sp_monitor - Shows statistics about Microsoft SQL Server.

Sp_prepare - Prepares a parameterized Transact-SQL statement and returns a statement handle for
execution.

Sp_pkeys - Returns primary key informations.

Sp_rename - Changes the name of a object in the current database.


Sp_renamedb - Changes a database name.

Sp_tables - Returns a list of objects like tables or views.

Sp_helptrigger - Returns the type or types of DML triggers defined on the specified table.

Sp_table_privileges - Returns a list of table permissions for the specified table.

Sp_server_info - Returns a list of attribute names and matching values for SQL Server.

Sp_statistics - Returns a list of all indexes and statistics on a specified table.

Sp_stored_procedures - Returns a list of stored procedures.

Sp_unprepare - Discards the execution plan created by the sp_prepare stored procedure.

Sp_updatestats - Runs UPDATE STATISTICS against all user-defined and internal tables in the current
database.

Sp_who - Returns information about current users, sessions, and processes in an instance of the SQL
Server.

System Stored Procedures can be executed using SQL Server Management Studio or any other tool
that supports SQL Server. They are an essential tool for managing and maintaining SQL Server
databases, and can help simplify and automate common administrative tasks

T-SQL Triggers

In this article we will learn how to use triggers in the Transact SQL server. A trigger is an object
created in the database that is automatically triggered when an event occurs. Events such as: insert,
update, delete.

The triggers are of several types: DML triggers, DDL triggers, LOGON triggers.

The most commonly used trigger is the DML type, and is created when using CREATE TRIGGER,
followed by the syntax ON {table_name | view_name} FOR INSERT, UPDATE, DELETE.

The ALTER TRIGGER syntax is used to modify the SQL statement inside a trigger.

In SQL Server database triggers can have status enabled or disabled.

The DROP TRIGGER syntax is used to delete a trigger from the database.

The T-SQL statement Create Trigger is used to create triggers: DML, DDL, Logon.

Create Trigger

The T-SQL statement Create Trigger is used to create triggers: DML, DDL, Logon.

DML Trigger

CREATE TRIGGER trig_name

ON { table_name | view_name }

{ FOR | AFTER | INSTEAD OF }


{ [ INSERT ] [ , ] [ UPDATE ] [ , ] [ DELETE ] }

AS { SQL statement [ ; ] }

GO

DDL Trigger

CREATE TRIGGER trig_name

ON { ALL SERVER | DATABASE }

{ FOR | AFTER }

{ CREATE, ALTER, DROP, GRANT, DENY, REVOKE, UPDATE STATISTICS }

AS { SQL statement [ ; ] }

GO

Logon Trigger

CREATE TRIGGER trig_name

ON ALL SERVER

{ FOR| AFTER }

LOGON

AS { SQL statement [ ; ] }

GO

Alter Trigger

The Alter Trigger command is used to modify triggers: DML, DDL, Logon.

ALTER TRIGGER trig_name

ON { table_name | view_name }

{ FOR | AFTER | INSTEAD OF }

{ [ INSERT ] [ , ] [ UPDATE ] [ , ] [ DELETE ] }

AS { SQL statement [ ; ] }

Go

Drop Trigger

To drop or delete a trigger uses the syntax Drop Trigger. The syntax is used for all types of triggers.

DROP TRIGGER trigger_name;

GO

Enable Trigger

To enable a trigger uses the syntax Enable Trigger. The syntax is used to enable one or all triggers.
ENABLE TRIGGER trigger_name ON table_name;

ALTER TABLE table_name ENABLE TRIGGER ALL;

ENABLE TRIGGER ALL ON ALL SERVER;

Disable Trigger

To disable a trigger uses the syntax Disable Trigger. The syntax is used to disable one or all triggers.

DISABLE TRIGGER trigger_name ON table_name;

ALTER TABLE table_name DISABLE TRIGGER ALL;

DISABLE TRIGGER ALL ON ALL SERVER;

Triggers in Object Catalog Views

To check a trigger uses T-SQL Object Catalog Views

select * from sys.triggers;

select * from sys.trigger_events;

select * from sys.trigger_event_types;

select * from sys.objects where type='TR' and type_desc='SQL_TRIGGER';

select * from sys.objects where type='TA' and type_desc='CLR_TRIGGER';

T-SQL Views

A T-SQL view is a virtual table and is created by a select composed of one or more tables.

A T-SQL view is composed of an SQL query.

Types of Views

Create View

The T-SQL statement Create View is used to create views.

CREATE VIEW view_name

AS

SQL statement

GO

Alter View

The T-SQL statement Alter View is used to modify an existing view.

ALTER VIEW view_name

AS
SQL statement

GO

Modify Rows From View

You can modify view records using the insert, update or delete commands.

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

UPDATE view_name SET column1=value1, column2=value2 WHERE column3=value3;

DELETE FROM view_name WHERE column1=value1;

Rename View

To rename view uses sp_rename command.

sp_rename 'OLD_VIEW_NAME', 'NEW_VIEW_NAME';

Drop View

To delete a view is used the command DROP VIEW.

DROP VIEW View_Name;

Views in Object Catalog Views

To check for a view information uses T-SQL Object Catalog Views.

select * from sys.views;

select * from sys.all_views where name='View_Name';

select * from sys.system_views where name='View_Name';

select * from sys.objects where type='VIEW';

Cursors – T SQL

In this section you can learn how to work with cursors using operations like declare cursor, create
procedure, fetch, delete, update, close, set, deallocate. To create a cursor, use the CURSOR DECLARE
syntax. When you declare a cursor, it is loaded with records, in order to access the records of the
cursor it must be opened using OPEN and the rows are returned using FETCH.

Declare cursor
The T-SQL statement DECLARE CURSOR is used to create and declare cursors. In the declarative part,
the cursor is created and loaded with values.

DECLARE cursor_name CURSOR

FOR sql_statement

Open cursor

The OPEN cursor statement opens a Transact-SQL server cursor

OPEN cursor_name | cursor_variable_name Fetch cursor

The FETCH cursor statement retrieves records from a Transact-SQL server cursor.

FETCH [ NEXT | PRIOR | FIRST | LAST ]

FROM cursor_name INTO cursor_variables;

Close cursor

The CLOSE cursor statement closes an open cursor by releasing the current result set. CLOSE leaves
the records available in cursor and allows the cursor to be reopened.

CLOSE cursor_name | cursor_variable_name

Deallocate cursor

The DEALLOCATE cursor statement delete the cursor.

DEALLOCATE cursor_name | cursor_variable_name

Cursor exampleIn the example below, we will create a cursor by going through all the steps that make
up the cursor.

In the declarative part we will DECLARE and load the cursor with records and we will also declare
variables to use them to display the information.

Once the cursor is created, we will open it using the OPEN statement, then process the cursor using
the FETCH statement and load variables with values.

CLOSE statement is used to close the cursor, then if it no longer needs to be opened it is destroyed
with DEALLOCATEstatement

Cursor operations

Create procedure - example in which a procedure is created and used in a cursor.

Delete - delete table rows with cursor.

Update - update table rows with cursor.

Cursor to insert records - uses cursor to insert records into table


T-SQL Backup and Restore SQL Server

This article describes the basics of backup and restore a SQL Server database.

T-SQL statements allow to back up and restore your SQL SERVER database.

Also, you can export and import security certificates and keys.

BACKUP DATABASE

The T-SQL statement BACKUP DATABASE is used to backup entire database to disk file.

USE model;

GO

BACKUP DATABASE model

TO DISK = 'E:\SQLServerBackup\model.bak'

WITH FORMAT,

MEDIANAME = 'SQLServerBackup',

NAME = 'Full Backup of model database';

GO

PARTIAL BACKUPS

The T-SQL statement BACKUP DATABASE READ_WRITE_FILEGROUPS is used to backup partial backup
to disk file.

USE model;

GO

BACKUP DATABASE model READ_WRITE_FILEGROUPS

TO DISK = 'E:\SQLServerBackup\model_partial.bak'

GO

Restore Data Base

The T-SQL statement RESTORE DATABASE is used to restore a SQL Server database.

USE model;

GO

RESTORE DATABASE model

FROM DISK = 'E:\SQLServerBackup\model.bak'

GO

RESTORE DATABASE WITH DIFFERENTIAL


The T-SQL statement RESTORE DATABASE WITH DIFFERENTIAL is used to restore full and differential
database backup.

--backup database with Differential

USE model;

GO

BACKUP DATABASE model

TO DISK = 'E:\SQLServerBackup\model_1.bak'

WITH DIFFERENTIAL;

GO

--restore database model

RESTORE DATABASE model

FROM DISK = 'E:\SQLServerBackup\model_1.bak'

GO

T-SQL Transaction Statements

A T-SQL transaction is a single logical unit of work and it is composed of several SQL Server
statements. The transaction begins with the first SQL Server statement executed and ends when the
transaction is saved or rolled back.

BEGIN DISTRIBUTED TRANSACTION

The T-SQL statement BEGIN DISTRIBUTED TRANSACTION specifies the start of a distributed
transaction.

BEGIN DISTRIBUTED { TRAN | TRANSACTION }

[ transaction_name | @transaction_name_variable ] ;

BEGIN Transaction

The T-SQL statement BEGIN TRANSACTION specifies the start of a local transaction.

BEGIN TRANSACTION transaction_name;

COMMIT TRANSACTION

The T-SQL statement COMMIT TRANSACTION specifies the end of a successful transaction.

COMMIT TRANSACTION transaction_name;


ROLLBACK Transaction

The T-SQL statement ROLLBACK TRANSACTION rollback a transaction to the start of the transaction,
or to a savepoint inside the transaction.

ROLLBACK TRANSACTION transaction_name;

ROLLBACK Work

The T-SQL statement ROLLBACK WORK specifies the rollback of a user specified transaction.

ROLLBACK WORK;

SAVE Transaction

The T-SQL statement SAVE TRANSACTION is used to create a savepoint within a transaction.

SAVE TRANSACTION savepoint_name;

Constraints T-SQL

In the Constraints sections you can learn how to create a SQL Primary Key Constraint or add a Foreign
Key to a table. Also you can learn how to use SQL Server commands to enable or disable keys. The
SQL Server constraints are Primary Key, Foreign Key, UNIQUE, CHECK and NOT NULL

Primary Key Constraints

The PRIMARY KEY consists of a column or a combination of several columns.

The columns of the primary key contain unique values that identify each row in a table.

The maximum number of columns allowed to compose a primary key is 16 columns and a total key
length of 900 bytes.

A table can contain only one primary key constraint.

PRIMARY KEY constraints do not allow for the value NULL.

Foreign Key Constraints

A FOREIGN KEY is a constraint is a relationship between two tables and used to enforce data
integrity. Foreign Key constraints can reference only tables within the same database on the same
server.

UNIQUE Constraints

UNIQUE constraints are used to prevent duplicate values from being inserted into specific columns in
a table.

UNIQUE constraints allow for the value NULL

CHECK Constraints

CHECK constraints specify the data values that are allowed in one or more columns.

CHECK constraints determine the valid values from a logical expression


T-SQL Expressions

This article describes how to use the T-SQL Expressions in SQL Server database. We will discuss in
detail the three main types of SQL Server expressions namely CASE, COALESCE and NULLIF.

Types of Expressions

There are three main types of SQL Server Expressions as follows:

CASE

COALESCE

NULLIF

What is CASE expression in SQL Server?

The CASE statement in SQL Server returns a specific output of value based on the condition specified
by the user. The SQL Server CASE statement has at least one pair of WHEN-THEN statements.

The WHEN statement consists of the condition to be applied to the table and tested, and the THEN
statement return the input expression once the WHEN statement returns TRUE. This also has an ELSE
statement, but it is optional. The ELSE statement has the activity to be done once any of the WHEN
statements don't return TRUE. Finally, the case statement ends with the END keyword

The syntax for the CASE statement

SELECT column1, column2,

CASE WHEN condition_expression THEN result_expression

ELSE else_result_expression

END AS column_name

FROM Table_name

In SQL Server you can use the CASE statement in WHERE clause.

What is COALESCE expression in SQL Server?

COALESCE expression in SQL Server has string manipulations. The method of obtaining another form
using the existing data is called String Manipulation.

COALESCE expression will return the data type which has the highest precedence data type. If the
entered expressions are nullable, the output will also be nullable

The syntax for COALESCE statement

COALESCE ( expression [ 1…n ] )


The properties of COALESCE

Expressions should be of the same type.

There can be multiple expressions.

First, check the integer, consisting of a character expression after the integer, which will give an
integer as an output

What is the NULLIF expression

NULLIF expression in SQL Server returns a NULL value when the given two parameters are identical,
and if it is not identical, it will return the value of the first parameter.

The syntax for NULLIF statement

NULLIF(expression_1, expression_2)

T-SQL Subquery

What is a Subquery

A SQL Subquery(also called an inner query or inner select) is a sql query that is nested inside a
statement(SELECT, INSERT, UPDATE, or DELETE), or inside another subquery.

Subquery basics

The statements that include a SQL Subquery usually use logical operators(in, exists, all, any or
some):

WHERE expression [NOT] IN (subquery)

WHERE expression comparison_operator [ANY | ALL | SOME] (subquery)

WHERE [NOT] EXISTS (subquery)

Rules for adding a subquery

A subquery in SQL Server database comes with the following restrictions that must be followed for
a successful addition to the outer query.

Only one expression or column name can be added to the list of a subquery introduced with a
comparison operator.

When the WHERE clause of a larger query consists of a column name, it shall be join-compatible with
the subquery select list column.

The select list 0 of subqueries does not accommodate the kinds of text, image, and text data.

The subquery that an untainted comparison operator adds cannot have clauses of GROUP BY or
HAVING. The reason is that they must give back a single value.

To those subqueries that include GROUP BY, the DISTINCT keyword cannot be added.
The clauses COMPUTE and INTO clauses cannot be defined.

Only when the top is defined ORDER BY can be defined.

When a view is created by using subquery, it cannot be updated

Subquery examples

IN

The IN operator verify that the value in a specified column matches any value in a subquery or list.

select * from EMPLOYEES E

where E.ID IN (select s.SalesPersonID from Sales s);

ANY

The ANY operator compares a scalar value with a single-column set of values.

select * from Customers c

where c.ID = ANY (select s.CustomerID from Sales s);

SOME

The SOME operator is equivalent with ANY operator.

select * from Students s

where s.id =SOME (select l.Student_id from Library l);

EXISTS

The Transact-SQL EXISTS operator specifies a subquery to check for the existence of rows.

select * from Students s

where EXISTS (select * from Students_Math m where m.id=s.id);

NOT EXISTS

The Transact-SQL NOT EXISTS operator specifies a subquery to check for the not existence of rows.

select * from Students s

where NOT EXISTS (select * from Students_Math m where m.id=s.id);

Correlated Subquery

In SQL Server, a correlated subquery is a type of subquery that refers to a column from the outer
query, and as a result, the subquery's results are dependent on the values in the outer query. This
type of subquery is also known as a dependent subquery.

A correlated subquery is typically used to retrieve data from one or more related tables based on the
data in the current row being processed in the outer query. It allows for more complex queries to be
performed, and can be particularly useful when dealing with large datasets
T-SQL Variables - Declare and Set variable

One of the key features of SQL Server that helps in managing and manipulating data efficiently is the
use of variables. Variables in SQL Server are used to store data temporarily during the execution of
code. They are essential in writing reusable, readable, and modular code. By using variables,
developers can write more flexible and dynamic SQL queries, enhancing the capability to handle data
dynamically during runtime. Understanding how to declare, initialize, and manipulate variables is
fundamental for anyone looking to master SQL Server programming.

In SQL Server, variables are used to store and manipulate data within a T-SQL script or a stored
procedure. Variables provide a way to store temporary values that can be used in various parts of a
script or procedure. They can hold different data types, such as integers, strings, dates, or other SQL
Server data types.

1. What is a Variable?

A Transact-SQL local variable is an database object that can store a single data value of a specific
type. Variables are particularly useful for temporarily storing data, which can be manipulated or
transferred as needed within batches, stored procedures, or scripts.

2. What are the types of variables?

The following are the two main types of SQL Server variables:

Local variables. They are declared by the user and start with the '@' symbol. Local variables can be
used within a procedure or batch. The scope of a local variable is limited to the batch or stored
procedure in which it is declared. Once the batch or procedure ends, the variable is de-allocated and
ceases to exist.

Global variables. They are declared by the system beforehand and start with the '@@' symbol.
Global variables can store session information. As these are system-defined, their lifecycle and scope
are managed by SQL Server itself, and they persist across different batches and sessions.

3. Declare a Transact-SQL Variable

To declare a variable uses the keyword DECLARE, assign a variable name and a data type. The
DECLARE statement of Transact-SQL will declare a variable as per the instruction given by the user.

Syntax for the DECLARE statement:

DECLARE @MyVariable datatype;

The following are the rules behind the DECLARE statement:

A name should be assigned by having '@' before itself.

A data type and length should be assigned. The most used date types are: INT, DATE, VARCHAR.

Initially, the value of the variable is set to null.

4. Set a Variable Value

After a variable is declared, it gets the default NULL value.

To assign a value to a variable, use the SET statement.


Syntax for the SET statement to set one variable:

DECLARE @Local_Variable Data_Type

SET @Local_Variable = Value

5. SELECT a Variable

The SELECT statement can be used to select the assigned values by certain criteria as per the
requirement of the user. Syntax for the SELECT statement of one variable or multiple variables:

DECLARE @Local_Variable Data_Type

SET @Local_Variable = Value

7. Conclusion

Variables are a fundamental aspect of SQL Server programming, enabling developers to write more
efficient, dynamic, and readable SQL scripts. Understanding how to properly declare, initialize, and
manage variables can significantly enhance your database operations. Practice is key to mastering
their use, so experimenting with different scenarios and applications will build your proficiency and
confidence in handling variables effectively in SQL Server.

You might also like