Master SQL Server From Scratch

Clear, interactive, and structured SQL Server lessons designed for beginners and developers.

COURSE SYLLABUS
1. Introduction to SQL Server
Introduction to SQL Server SQL Server Installation SQL Server Fundamentals
2. Data Types
Data Types Numeric Data Types Character & String Data Types Date & Time Data Types Other SQL Server Data Types
3. Database & Tables
Database & Tables Introduction Creating a Database Creating Tables Table Structure Altering Tables Dropping Tables
4. Constraints
Constraints Introduction PRIMARY KEY FOREIGN KEY UNIQUE Constraint NOT NULL & DEFAULT CHECK Constraint
5. SQL Basics
SQL Basics Introduction SQL Commands SQL Command Categories SELECT Statement INSERT, UPDATE & DELETE
6. CRUD Operations
CRUD Operations Introduction INSERT Operation SELECT Operation UPDATE Operation DELETE Operation
7. SQL Queries
Queries Introduction WHERE Clause ORDER BY Clause DISTINCT LIKE Operator IN, BETWEEN & IS NULL
8. Joins
Joins Introduction INNER JOIN LEFT JOIN RIGHT JOIN FULL OUTER JOIN CROSS JOIN
9. SQL Functions
SQL Functions Introduction String Functions Numeric Functions Date & Time Functions Conversion Functions NULL Functions
10. Grouping & Aggregate Functions
GROUP BY Aggregate Functions COUNT() SUM() AVG() MIN() & MAX()
11. Subqueries
Subqueries Introduction Single-Row Subquery Multiple-Row Subquery Correlated Subquery Subquery with DML
12. Views
SQL Views Introduction Creating a View Updating a View Altering a View Dropping a View
13. Stored Procedures
Stored Procedures Introduction Creating a Stored Procedure Input Parameters Output Parameters Executing & Modifying Stored Procedures
14. Triggers
Triggers Introduction AFTER INSERT Trigger AFTER UPDATE Trigger AFTER DELETE Trigger INSTEAD OF Trigger
15. Transactions
Transactions Introduction COMMIT ROLLBACK SAVEPOINT Transaction with TRY...CATCH
16. Indexes
Indexes Introduction Clustered Index Non-Clustered Index Creating & Dropping Indexes Index Performance
17. Common Table Expressions
CTE Introduction Simple CTE CTE with JOIN CTE with Aggregate Functions Recursive CTE
18. Window Functions
Window Functions Introduction ROW_NUMBER() RANK() and DENSE_RANK() LEAD() and LAG() PARTITION BY
19. Advanced SQL
Advanced SQL Introduction Temporary Tables Table Variables Dynamic SQL Error Handling Performance Optimization

Transaction with TRY...CATCH

Learn how TRY...CATCH can be used with SQL Server Transactions to handle errors and safely commit or roll back database changes.

What is TRY...CATCH?

TRY...CATCH is used in SQL Server to handle errors that occur while executing SQL statements.

The statements that may generate an error are placed inside the TRY block. If an error occurs, SQL Server transfers control to the CATCH block.

Basic TRY...CATCH Syntax

BEGIN TRY

    -- SQL statements

END TRY

BEGIN CATCH

    -- Error handling

END CATCH;

Transaction with TRY...CATCH

A transaction can be combined with TRY...CATCH so that successful operations are committed and failed operations are rolled back.

BEGIN TRY

    BEGIN TRANSACTION;

    -- SQL statements

    COMMIT TRANSACTION;

END TRY

BEGIN CATCH

    ROLLBACK TRANSACTION;

END CATCH;

Simple Example

BEGIN TRY

    BEGIN TRANSACTION;

    INSERT INTO Students
    (
        StudentId,
        StudentName,
        City,
        Age
    )
    VALUES
    (
        501,
        'Rahul',
        'Pune',
        22
    );

    COMMIT TRANSACTION;

END TRY

BEGIN CATCH

    ROLLBACK TRANSACTION;

END CATCH;

If the INSERT operation succeeds, the transaction is committed. If an error occurs, the CATCH block executes and the transaction is rolled back.

Handling the Error Message

SQL Server provides functions that can be used inside the CATCH block to retrieve information about an error.

BEGIN TRY

    BEGIN TRANSACTION;

    -- SQL statements

    COMMIT TRANSACTION;

END TRY

BEGIN CATCH

    IF @TRANCOUNT > 0
        ROLLBACK TRANSACTION;

    SELECT
        ERROR_NUMBER() AS ErrorNumber,
        ERROR_MESSAGE() AS ErrorMessage,
        ERROR_LINE() AS ErrorLine;

END CATCH;

Important Error Functions

Function Purpose
ERROR_NUMBER() Returns the error number.
ERROR_MESSAGE() Returns the error message.
ERROR_LINE() Returns the line number where the error occurred.
ERROR_PROCEDURE() Returns the name of the stored procedure where the error occurred, when applicable.
ERROR_SEVERITY() Returns the severity level of the error.
ERROR_STATE() Returns the state number of the error.

Why Check @TRANCOUNT?

@TRANCOUNT returns the number of active transactions for the current session.

Before executing ROLLBACK TRANSACTION in the CATCH block, it is useful to check whether a transaction is currently active.

IF @TRANCOUNT > 0
    ROLLBACK TRANSACTION;

Complete Transaction Example

BEGIN TRY

    BEGIN TRANSACTION;

    INSERT INTO Students
    (
        StudentId,
        StudentName,
        City,
        Age
    )
    VALUES
    (
        502,
        'Priya',
        'Mumbai',
        21
    );

    UPDATE Students
    SET Age = Age + 1
    WHERE StudentId = 502;

    COMMIT TRANSACTION;

    PRINT 'Transaction completed successfully.';

END TRY

BEGIN CATCH

    IF @TRANCOUNT > 0
        ROLLBACK TRANSACTION;

    SELECT
        ERROR_NUMBER() AS ErrorNumber,
        ERROR_MESSAGE() AS ErrorMessage,
        ERROR_LINE() AS ErrorLine;

END CATCH;

Transaction with TRY...CATCH Flow

Step 1: Start TRY block.

↓
Step 2: Begin Transaction.

↓
Step 3: Execute SQL statements.

↓
Step 4: Check result.

↓
If successful: COMMIT Transaction.

If error occurs: Execute CATCH block.

↓
ROLLBACK Transaction.

COMMIT and ROLLBACK with TRY...CATCH

Situation Action
All operations succeed. COMMIT TRANSACTION
An error occurs. ROLLBACK TRANSACTION
Need error details. Use ERROR_* functions.

Important Points

  • TRY contains the statements that may generate an error.
  • CATCH handles errors generated inside the TRY block.
  • BEGIN TRANSACTION starts the transaction.
  • COMMIT TRANSACTION saves successful changes.
  • ROLLBACK TRANSACTION undoes uncommitted changes.
  • @TRANCOUNT can be checked before rolling back.
  • ERROR_MESSAGE() and other ERROR_* functions can provide information about the error.

Summary

Using TRY...CATCH with transactions provides a structured way to handle database errors.

When all operations are successful, the transaction is committed. If an error occurs, the CATCH block can roll back the transaction and return useful error information.