T-SQL Fundamentals

Introduction to T-SQL

Transact-SQL (T-SQL) is Microsoft's procedural extension to SQL (Structured Query Language). It is used to interact with Microsoft SQL Server. T-SQL enhances SQL by adding procedural programming elements such as variables, control-flow statements, and error handling.

This document covers the fundamental concepts of T-SQL, providing a foundation for writing efficient and powerful queries and scripts for SQL Server.

Basic SQL Statements in T-SQL

T-SQL supports standard SQL data manipulation language (DML) and data definition language (DDL) statements.

Data Query Language (DQL)

Data Manipulation Language (DML)

Data Definition Language (DDL)

Common T-SQL Data Types

Understanding data types is crucial for efficient data storage and manipulation. Here are some of the most common ones:

Data Type Description Example Usage
INT Integer numbers. DECLARE @count INT = 10;
VARCHAR(n) Variable-length non-Unicode character string. DECLARE @name VARCHAR(50) = 'Alice';
NVARCHAR(n) Variable-length Unicode character string. DECLARE @message NVARCHAR(200) = N'Hello World';
DATE Date values (year, month, day). DECLARE @event_date DATE = '2023-10-27';
DATETIME Date and time values. DECLARE @log_time DATETIME = '2023-10-27 10:30:00';
DECIMAL(p,s) Fixed-precision and scale numeric values. DECLARE @price DECIMAL(10, 2) = 19.99;
BIT Integer that can be 0, 1, or NULL. Often used for Boolean values. DECLARE @is_active BIT = 1;

Operators in T-SQL

T-SQL uses various operators for comparisons, arithmetic, and logical operations.

-- Example using operators
DECLARE @num1 INT = 10;
DECLARE @num2 INT = 5;
DECLARE @sum INT;
DECLARE @message VARCHAR(50);

SET @sum = @num1 + @num2; -- Arithmetic
SET @message = 'Result is: ' + CAST(@sum AS VARCHAR(10)); -- String concatenation

SELECT @num1 > @num2; -- Comparison (returns 1 for true)
SELECT @num1 <> @num2 OR @num1 = 10; -- Logical

Control Flow Statements

Control flow statements allow you to add logic and decision-making to your T-SQL scripts.

Built-in Functions

SQL Server provides a rich set of built-in functions for various purposes:

-- Example using functions
DECLARE @current_date DATE = GETDATE();
DECLARE @tomorrow DATE = DATEADD(day, 1, @current_date);

SELECT COUNT(*) AS TotalCustomers
FROM Customers
WHERE City = 'London';

Stored Procedures

Stored procedures are precompiled SQL statements stored in the database. They offer benefits like improved performance, reusability, and enhanced security.

-- Creating a stored procedure
CREATE PROCEDURE GetCustomerByID
    @CustomerID INT
AS
BEGIN
    SELECT CustomerName, Email
    FROM Customers
    WHERE CustomerID = @CustomerID;
END;
GO

-- Executing a stored procedure
EXEC GetCustomerByID @CustomerID = 101;

Views

Views are virtual tables based on the result-set of an SQL statement. They can simplify complex queries and provide a security layer.

-- Creating a view
CREATE VIEW ActiveCustomers AS
SELECT CustomerID, CustomerName, Email
FROM Customers
WHERE IsActive = 1;
GO

-- Querying a view
SELECT CustomerName, Email
FROM ActiveCustomers;

Triggers

Triggers are special stored procedures that automatically execute or fire when an event (like an INSERT, UPDATE, or DELETE statement) occurs on a table. They are often used for enforcing business rules or maintaining data integrity.

-- Example of an AFTER INSERT trigger
CREATE TRIGGER trg_AuditInsert
ON Orders
AFTER INSERT
AS
BEGIN
    INSERT INTO OrderAudit (OrderID, Action, AuditDate)
    SELECT OrderID, 'INSERT', GETDATE()
    FROM INSERTED; -- The 'inserted' virtual table contains the new rows
END;
GO

This covers the essential T-SQL fundamentals. For more advanced topics, refer to specific documentation on functions, error handling, transactions, and more.