T-SQL
T-SQL (TRANSACT-SQL)
• T-SQL (Transact-SQL) is Microsoft’s proprietary extension of SQL
(Structured Query Language).
• It’s the main language used to interact with Microsoft SQL Server and
Azure SQL Database. While standard SQL provides the core commands
for querying and manipulating data (SELECT, INSERT, UPDATE, DELETE,
etc.), T-SQL adds extra features that make it more powerful for
building real-world database applications.
KEY FEATURES OF T-SQL
• Procedural Programming:
• Variables (DECLARE @Name VARCHAR(50))
• Control flow statements (IF, WHILE, BEGIN…END)
• Error Handling:
• TRY...CATCH blocks for handling exceptions
• Built-in Functions:
• Date functions (GETDATE(), DATEADD())
• String functions (LEN(), SUBSTRING())
• Math functions (ROUND(), ABS())
KEY FEATURES OF T-SQL (CONT’)
• Transactions:
• Ensures data consistency with BEGIN TRANSACTION, COMMIT, and ROLLBACK.
• Stored Procedures and Triggers:
• Reusable code modules stored in the database.
• Advanced Querying:
• Common Table Expressions (CTEs)
• Window functions (ROW_NUMBER(), RANK(), OVER())
EXAMPLE
T-SQL
SCRIPT:
HOW TO
SET VALUES
IN T-SQL?
YOU CAN USE EITHER SET
OR SELECT.
SET
Assigns one value to a variable.
If the query returns more than one row, it raises an
error.
SET(EXAMPL
E)
SELECT
Can assign values to one or
many variables.
If the query returns more
than one row:
The last row’s value
is stored.
Often used for performance
when setting multiple
variables in one go.
EXAMPLE OF SELECT
COMMON ERRORS
Data type mismatch
Rounding errors: Assigning a money data type
to an integer
removes the cents
COMMON ERRORS(CONT’)
Insufficient space: assigning a 12 character string to a variable defined
as char(10)
CASTING
• convert one data type into another.
• Concatenate string and number
Example: PRINT 'Ahmad' + CAST(12 AS CHAR(2));
• Assign casted value to variable
IF … ELSE
IF..ELSE
(WITH
QUERY)
WHILE LOOP
• Increase book prices until average is >= 40
T-SQL CURSOR
• A cursor in T-SQL is a
database object that lets you
process rows one at a time
from a result set.
• A cursor works like a pointer
that moves through a query
result row by row.
PRACTICAL
PART
• Create Table Students.
• Insert Values
QUESTION 1: WHAT WILL BE THE OUTPUT?
Output: Ali
QUESTION 2: WHAT WILL HAPPEN HERE?
Answer: Error Occurs because It returned more than 1 value.
QUESTION 2: WHAT WILL BE THE OUTPUT?
Answer: Omar (last row’s value appear)
QUESTION 4: WHAT IS OUTPUT?