A comprehensive collection of T-SQL scripts covering advanced SQL Server programming concepts. This repository serves as a practical learning resource and reference guide for mastering T-SQL fundamentals and advanced techniques.
This repository contains 15 structured modules with hands-on T-SQL scripts that progressively cover SQL Server programmingβfrom basic variable declaration to advanced topics like recursive CTEs, triggers, and dynamic SQL. Each module includes multiple practical examples with clear comments and real-world scenarios.
This project was developed as part of my journey to master advanced T-SQL programming. It represents practical implementations of concepts learned, focusing on:
- Building a strong foundation in SQL Server procedural programming
- Understanding database programming patterns used in enterprise applications
- Developing skills for writing efficient, maintainable, and secure T-SQL code
- Preparing for real-world database development scenarios
Note: This is an educational repository designed for learning and reference purposes, not a production application.
| Technology | Purpose |
|---|---|
| Microsoft SQL Server | Database engine |
| T-SQL | Query and programming language |
| SQL Server Management Studio (SSMS) | Development environment |
TSQL-Advanced-Concepts/
β
βββ 01_Variables/ # Variable declaration and assignment
βββ 02_IfStatment/ # Conditional logic with IF statements
βββ 03_CaseStatement/ # CASE expressions and conditional queries
βββ 04_WhileLoop/ # Iterative processing with WHILE loops
βββ 05_ErrorHandling_TryCatch/ # Exception handling and error management
βββ 06_Transactions/ # Transaction control and ACID compliance
βββ 07_TempTable/ # Temporary tables and table variables
βββ 08_StoredProcedures/ # Creating and managing stored procedures
βββ 09_BuiltInFunctions/ # String, date, and aggregate functions
βββ 10_WindowFunctions/ # ROW_NUMBER, RANK, LAG/LEAD, pagination
βββ 11_ScalarAndTableValuedFunctions/ # User-defined functions (UDFs)
βββ 12_DynamicSqlAndSqlInjection/ # Dynamic SQL and security awareness
βββ 13_Triggers/ # AFTER and INSTEAD OF triggers
βββ 14_Cursors/ # Cursor types and row-by-row processing
βββ 15_CTE/ # Common Table Expressions and recursion
β
βββ SampleDatabaseBackup/ # Sample database backup file (.bak)
βββ LICENSE # MIT License
βββ README.md # This file
- Declaration and assignment using
SETandSELECT - Practical examples: Employee reports, sales summaries, loyalty points calculation
- Simple, nested, and compound conditional logic
- Integration with
EXISTS,AND,OR,NOToperators - Error handling patterns with IF
- Simple CASE as switch-like expressions
- CASE in
ORDER BYfor custom sorting - Conditional updates and aggregations with
GROUP BY
- Counters, table iteration, and conditional exits
- Nested loops (multiplication tables)
BREAKandCONTINUEcontrol flow
- Exception handling syntax and best practices
- Error functions:
ERROR_NUMBER(),ERROR_MESSAGE(),ERROR_STATE() - Custom error throwing with
THROW @@ERRORand@@ROWCOUNTsystem variables
- Bank transfer simulation with full validation
- Production-level transaction handling
- Commit and rollback patterns
- Table variables vs. temporary tables
- Scope and performance considerations
- CRUD operations with stored procedures
- Input/output parameters and return values
- Using
sp_helptextfor procedure inspection
- String manipulation functions
- Date/time functions
- Aggregate functions
- Ranking:
ROW_NUMBER(),RANK(),DENSE_RANK() - Partitioning with
PARTITION BY - Analytics:
LAG()andLEAD() - Pagination with
OFFSET FETCH
- Scalar functions
- Inline table-valued functions
- Multi-statement table-valued functions
- Building and executing dynamic queries
- SQL injection demonstration for security awareness
AFTER INSERT/UPDATE/DELETEtriggersINSTEAD OFtriggers for complex logic- Audit logging patterns
- Static, dynamic, forward-only, and scrollable cursors
- Understanding cursor types and their use cases
- Basic CTE syntax
- Recursive CTEs for hierarchical data
- Practical examples: Employee hierarchies, date series generation, duplicate detection, ranking
Through building this repository, I developed proficiency in:
| Skill | Description |
|---|---|
| Procedural T-SQL | Writing efficient control flow with variables, loops, and conditions |
| Error Handling | Implementing robust TRY...CATCH blocks and custom error management |
| Transaction Management | Ensuring data integrity with proper commit/rollback patterns |
| Performance Optimization | Understanding when to use temp tables, CTEs, and window functions |
| Security Awareness | Recognizing SQL injection vulnerabilities and prevention techniques |
| Modular Code | Creating reusable stored procedures and functions |
| Advanced Queries | Leveraging window functions, CTEs, and dynamic SQL |
| Database Triggers | Implementing audit trails and business rule enforcement |
- Microsoft SQL Server (2016 or later recommended)
- SQL Server Management Studio (SSMS) or Azure Data Studio
- Clone this repository:
git clone https://github.com/yourusername/TSQL-Advanced-Concepts.git
- Open SSMS and connect to your SQL Server instance
- Restore the sample database from
SampleDatabaseBackup/folder (see Database Setup section) - Navigate to any module folder and open the
.sqlfiles
- Restore the sample database from
SampleDatabaseBackup/folder (recommended for best experience) - Open any
.sqlfile in SSMS or Azure Data Studio - Connect to your SQL Server instance
- Ensure you're using the restored sample database (
USE SampleDB;) - Execute scripts in numerical order within each module
- Review the comments for explanations and expected results
Tip: Restoring the sample database ensures all required tables and sample data are available for the scripts to work correctly.
A ready-to-use sample database backup is included in the SampleDatabaseBackup/ folder. This is the easiest way to get started:
- Locate the backup file in
SampleDatabaseBackup/SampleDatabaseBackup - Restore the database using SSMS:
- Right-click Databases β Restore Database...
- Select Device β Click ... β Add β Browse to the backup file
- Click OK to restore
- Or use T-SQL:
RESTORE DATABASE SampleDB FROM DISK = 'C:\Path\To\SampleDatabaseBackup\SampleDatabaseBackup' WITH MOVE 'SampleDB' TO 'C:\SQL\Data\SampleDB.mdf', MOVE 'SampleDB_log' TO 'C:\SQL\Data\SampleDB_log.ldf', REPLACE;
Note: Adjust the file paths according to your SQL Server installation.
If you prefer to create tables manually, use these sample structures:
-- Example: Students table used in multiple modules
CREATE TABLE Students (
StudentID INT IDENTITY(1,1) PRIMARY KEY,
Name NVARCHAR(50),
Subject NVARCHAR(50),
Grade INT
);
-- Example: Employees table
CREATE TABLE Employees (
EmployeeId INT IDENTITY(1,1) PRIMARY KEY,
Name NVARCHAR(100),
DepartmentId INT,
ManagerID INT NULL
);
-- Example: Accounts table for transaction demos
CREATE TABLE Accounts (
AccountID INT PRIMARY KEY,
Balance DECIMAL(10,2)
);Note: Specific table structures may vary per script. Refer to individual scripts for exact requirements.
- Scripts are designed for learning purposes and may require adaptation for production use
- Sample data and table structures should be created before running certain scripts
- Some modules reference tables like
Students,Employees,Departments, andAccounts - The SQL injection example in Module 12 is for educational awareness onlyβnever use such patterns in production
This repository represents my practical journey through advanced T-SQL programming. Each module builds upon the previous, creating a comprehensive reference for SQL Server development patterns.
Whether you're learning T-SQL, preparing for interviews, or looking for quick reference examples, I hope this collection proves useful.
This project is licensed under the MIT License - see the LICENSE file for details.
Mohamed Ragheb
β If you find this repository helpful, please consider giving it a star!