Paramclasses Academy - Blog

Tutorials Details

←
Post 38 of 40
→

SQL Server Dynamic SQL and Temporary Tables Explained with Practical Examples

SQL Server Dynamic SQL and Temporary Tables Explained with Practical Examples

November 18, 2026

SQL Server Dynamic SQL and Temporary Tables Explained

Microsoft SQL Server provides several advanced features that help developers write flexible, reusable, and efficient database queries. Two important concepts used in advanced SQL development are Dynamic SQL and Temporary Tables.

Dynamic SQL allows developers to build and execute SQL statements dynamically at runtime. Temporary Tables allow developers to store intermediate results temporarily while performing complex database operations.

These features are commonly used in reporting systems, employee management applications, inventory management software, billing systems, and enterprise database applications.

In this tutorial, we will understand Dynamic SQL, its execution methods, Temporary Tables, their types, practical SQL examples, advantages, disadvantages, and important security considerations.

At Param Classes, students can learn these advanced SQL Server concepts through practical examples and database development exercises.

1. What Is Dynamic SQL in SQL Server?

Dynamic SQL is a technique used to create and execute SQL statements dynamically during program execution.

In normal SQL queries, the statement is written directly with fixed table names, column names, and conditions.

However, sometimes an application needs to generate queries based on user selections or changing requirements.

For example:

  • A user wants to search employees by different departments.

  • An administrator wants to select different database tables.

  • A report needs to filter records based on a selected date.

  • An application needs to generate different queries according to user input.

Dynamic SQL makes these operations possible.

Simple Example:

DECLARE @SQL NVARCHAR(MAX);

SET @SQL = 'SELECT * FROM Employees';

EXEC(@SQL);

Explanation:

  • DECLARE creates a variable.

  • @SQL stores the SQL statement.

  • SET assigns the query to the variable.

  • EXEC() executes the dynamically generated statement.

???? Important: Dynamic SQL is useful when query structure changes at runtime. For ordinary queries with fixed conditions, normal parameterized SQL is generally preferable.

2. Understanding EXEC() in Dynamic SQL

SQL Server provides the EXEC() statement to execute dynamically generated SQL commands.

Basic Syntax

EXEC(@SQL);

Practical Example: Display Employee Records

DECLARE @SQL NVARCHAR(MAX);

SET @SQL = '
SELECT
    EmployeeID,
    EmployeeName,
    Salary
FROM Employees';

EXEC(@SQL);

This query executes the SQL statement stored inside the variable.

Example: Dynamic WHERE Condition

DECLARE @Department NVARCHAR(50);
DECLARE @SQL NVARCHAR(MAX);

SET @Department = 'IT';

SET @SQL = '
SELECT *
FROM Employees
WHERE Department = ''' + @Department + '''';

EXEC(@SQL);

Expected Result: The query displays employees belonging to the IT department.

⚠️ Security Warning: Building SQL statements by directly concatenating user-provided values can create SQL Injection vulnerabilities. Prefer sp_executesql with parameters for values.

3. What Is sp_executesql in SQL Server?

sp_executesql is a system stored procedure used to execute dynamic SQL statements with parameters.

It is generally preferred over string concatenation when passing variable values into dynamic queries.

Basic Syntax

EXEC sp_executesql
    @SQL,
    @ParameterDefinition,
    @ParameterValue;

Practical Example

DECLARE @SQL NVARCHAR(MAX);

SET @SQL = '
SELECT *
FROM Employees
WHERE Department = @Dept';

EXEC sp_executesql
    @SQL,
    N'@Dept NVARCHAR(50)',
    @Dept = N'IT';

How It Works:

  1. @SQL stores the dynamic query.

  2. @Dept is declared as a parameter.

  3. sp_executesql executes the query.

  4. SQL Server uses the supplied parameter value.

Advantages of sp_executesql

  • Supports parameterized dynamic queries.

  • Helps reduce SQL Injection risks when used correctly.

  • Can improve execution plan reuse.

  • Makes dynamic query code easier to maintain.

  • Supports multiple input and output parameters.

Best Practice: Use parameters for dynamic query values. Table names and column names cannot be passed as ordinary SQL parameters; validate and safely quote those identifiers using techniques such as QUOTENAME().

4. What Are Temporary Tables in SQL Server?

A Temporary Table is a table created to store intermediate data during database operations.

Temporary Tables are especially useful when a query requires multiple processing steps.

SQL Server stores temporary tables in the tempdb system database.

They are commonly used for:

  • Intermediate query results.

  • Complex reporting operations.

  • Data filtering and transformation.

  • Multi-step calculations.

  • Temporary storage during stored procedure execution.

Basic Syntax

CREATE TABLE #Students
(
    StudentID INT,
    StudentName VARCHAR(100),
    Course VARCHAR(100)
);

Here, #Students is a local temporary table.

Important: Temporary Tables are temporary database objects, not permanent tables in your application database.

5. Types of Temporary Tables in SQL Server

SQL Server primarily supports two common types of temporary tables.

A. Local Temporary Table (#TableName)

A Local Temporary Table starts with a single hash symbol (#).

It is generally visible only within the session that created it, with additional scope rules for nested procedures.

Example:

CREATE TABLE #EmployeeTemp
(
    EmployeeID INT,
    EmployeeName VARCHAR(100),
    Salary DECIMAL(10,2)
);

Insert records:

INSERT INTO #EmployeeTemp
VALUES
(1, 'Rahul', 50000),
(2, 'Priya', 45000),
(3, 'Amit', 60000);

Display records:

SELECT *
FROM #EmployeeTemp;

The temporary table remains available within its applicable scope until it is dropped or its session ends.

B. Global Temporary Table (##TableName)

A Global Temporary Table starts with two hash symbols (##).

It can be accessed by other sessions while the table exists and is subject to SQL Server's global temporary table lifetime rules.

Example:

CREATE TABLE ##EmployeeData
(
    EmployeeID INT,
    EmployeeName VARCHAR(100)
);

Insert records:

INSERT INTO ##EmployeeData
VALUES
(1, 'Rahul'),
(2, 'Priya');

Retrieve records:

SELECT *
FROM ##EmployeeData;

Important: Global Temporary Tables may be visible to multiple sessions. Avoid storing sensitive information in them without appropriate access controls.

6. Difference Between Local and Global Temporary Tables

Feature Local Temporary Table Global Temporary Table
Prefix # ##
Visibility Creating session and applicable scope Multiple sessions
Lifetime Session or applicable scope Until the last referencing session finishes
Common use Individual session processing Shared temporary data
Name #Students ##Students

Remember: Use Local Temporary Tables for most session-specific operations. Use Global Temporary Tables only when cross-session visibility is genuinely required.

7. How to Insert and Retrieve Data Using Temporary Tables

Let's understand a practical Student Management System example.

Suppose you want to temporarily store students who have scored more than 70 marks.

Step 1: Create a Temporary Table

CREATE TABLE #TopStudents
(
    StudentID INT,
    StudentName VARCHAR(100),
    Marks INT
);

Step 2: Insert Records

INSERT INTO #TopStudents
VALUES
(1, 'Rahul', 85),
(2, 'Priya', 92),
(3, 'Amit', 78);

Step 3: Retrieve Records

SELECT *
FROM #TopStudents
WHERE Marks > 80;

Expected Result: Rahul and Priya will appear because their marks are greater than 80.

???? Practical Tip: Temporary Tables are useful when the output of one query must be processed by another query without creating permanent database tables.

8. Difference Between Temporary Tables and Table Variables

SQL Server also supports Table Variables, which are another option for storing intermediate data.

Example:

DECLARE @StudentData TABLE
(
    StudentID INT,
    StudentName VARCHAR(100)
);

INSERT INTO @StudentData
VALUES
(1, 'Rahul'),
(2, 'Priya');

SELECT *
FROM @StudentData;

Comparison:

Feature Temporary Table Table Variable
Declaration CREATE TABLE DECLARE
Name #Table @Table
Storage tempdb tempdb-backed storage
Indexing Supports indexes Supports certain indexes and constraints
Scope Session/procedure scope Batch, procedure or function scope
Statistics Supports column statistics Statistics behavior is more limited

Note: Performance depends on SQL Server version, data volume, indexes, and query complexity. Do not assume that Table Variables are always faster than Temporary Tables.

9. Combining Dynamic SQL with Temporary Tables

Dynamic SQL and Temporary Tables can be used together to perform advanced database operations.

Practical Example:

CREATE TABLE #EmployeeTemp
(
    EmployeeID INT,
    EmployeeName VARCHAR(100),
    Salary DECIMAL(10,2)
);

INSERT INTO #EmployeeTemp
VALUES
(1, 'Rahul', 50000),
(2, 'Priya', 45000),
(3, 'Amit', 60000);

DECLARE @SQL NVARCHAR(MAX);

SET @SQL = '
SELECT *
FROM #EmployeeTemp
WHERE Salary > @MinimumSalary';

EXEC sp_executesql
    @SQL,
    N'@MinimumSalary DECIMAL(10,2)',
    @MinimumSalary = 48000;

DROP TABLE #EmployeeTemp;

Explanation:

  • First, a temporary table is created.

  • Employee records are inserted.

  • Dynamic SQL is generated.

  • sp_executesql executes the query with a salary parameter.

  • The temporary table is dropped after use.

This example demonstrates how both features can work together in a single SQL Server workflow.

10. Common Mistakes and Best Practices

⚠️ Common Mistakes:

  • Using dynamic SQL without validating user input.

  • Creating unnecessary temporary tables.

  • Forgetting to clean up temporary objects when appropriate.

  • Confusing local and global temporary table scope.

  • Assuming all dynamic queries improve performance.

  • Using string concatenation instead of parameterized queries for user-provided values.

Best Practices:

  • Prefer sp_executesql for parameterized dynamic queries.

  • Use QUOTENAME() for validated dynamic identifiers.

  • Use temporary tables when intermediate results need to be reused.

  • Avoid unnecessary global temporary tables.

  • Choose suitable data types.

  • Test complex queries with realistic data.

  • Monitor query performance and tempdb usage.

11. Real-World Applications

Dynamic SQL and Temporary Tables are widely used in professional applications.

Student Management System: Generate dynamic reports based on course, marks, and admission year.

Employee Management System: Create department-wise salary reports and temporarily store filtered employee information.

Inventory Management System: Generate product reports based on category, stock level, and supplier.

Billing Management System: Prepare temporary transaction summaries and dynamically generate financial reports.

At Param Classes, students can practice these concepts by creating sample databases and developing practical SQL queries used in real-world application development.

Conclusion

Dynamic SQL and Temporary Tables are important advanced features of Microsoft SQL Server. Dynamic SQL provides flexibility by allowing queries to be generated and executed at runtime, while Temporary Tables help store intermediate results for multi-step database operations.

By understanding EXEC(), sp_executesql, Local Temporary Tables, Global Temporary Tables, and Table Variables, developers can write more flexible and organized SQL queries.

Whether you are developing a Student Management System, Inventory Application, Employee Database, or Billing Software, these concepts can help you handle complex database operations more effectively.

Learn Advanced SQL Server with Param Classes and strengthen your database development skills through practical training and real-world projects.

←
Post 38 of 40
→