Skip to main content

SQL : Temp Tables, Table-Valued Parameters, Global Temp Tables, and CTEs


Structured Query Language (SQL) is a powerful tool for managing and querying databases.

In this blog post, we'll delve into some SQL Server features that are often used in different scenarios: Temp Tables, Table-Valued Parameters, Global Temp Tables, and Common Table Expressions (CTEs).

We'll explore each concept, provide SQL Server code snippets, and discuss when to use each.

Temp Tables

Temp Tables are temporary storage structures that exist only for the duration of a session or a batch.

They are used to store and process intermediate results during complex queries.
-- Create a Temp Table
CREATE TABLE #TempTable (
    ID INT PRIMARY KEY,
    Name NVARCHAR(50)
);
 
-- Insert data into Temp Table
INSERT INTO #TempTable (ID, Name)
VALUES (1, 'John'), (2, 'Jane');
 
-- Query Temp Table
SELECT * FROM #TempTable;
 
-- Drop Temp Table at the end of the session or batch
DROP TABLE #TempTable;

Table-Valued Parameters (TVPs)

Table-Valued Parameters allow you to pass a table structure as a parameter to a stored procedure or a function.

They are useful when you need to pass multiple rows of data to a stored procedure or function.
-- Create a User-Defined Table Type
CREATE TYPE dbo.EmployeeType AS TABLE (
    ID INT,
    Name NVARCHAR(50)
);
 
-- Create a stored procedure using TVP
CREATE PROCEDURE usp_InsertEmployees
    @Employees dbo.EmployeeType READONLY
AS
BEGIN
    INSERT INTO Employees (ID, Name)
    SELECT ID, Name FROM @Employees;
END;
 
-- Declare a variable of TVP type
DECLARE @EmployeeData dbo.EmployeeType;
 
-- Insert data into TVP variable
INSERT INTO @EmployeeData (ID, Name)
VALUES (1, 'Alice'), (2, 'Bob');
 
-- Execute stored procedure with TVP
EXEC usp_InsertEmployees @Employees = @EmployeeData;

Global Temp Tables

Global Temp Tables are similar to Temp Tables, but their scope extends beyond a single session.

They persist until all sessions referencing them complete.
-- Create a Global Temp Table
CREATE TABLE ##GlobalTempTable (
    ID INT PRIMARY KEY,
    Name NVARCHAR(50)
);
 
-- Insert data into Global Temp Table
INSERT INTO ##GlobalTempTable (ID, Name)
VALUES (1, 'Mike'), (2, 'Sara');
 
-- Query Global Temp Table
SELECT * FROM ##GlobalTempTable;
 
-- Drop Global Temp Table explicitly when no longer needed
DROP TABLE ##GlobalTempTable;

Common Table Expressions (CTEs)

CTEs are named result sets that can be referred to within a SELECT, INSERT, UPDATE, or DELETE statement.

They are useful for simplifying complex queries and enhancing code readability.
-- Create a Common Table Expression (CTE)
WITH DepartmentCTE AS (
    SELECT
        ID,
        Name,
        ManagerID
    FROM
        Departments
    WHERE
        Location = 'Headquarters'
)
-- Use the CTE in a SELECT statement
SELECT
    E.EmployeeID,
    E.EmployeeName,
    DCTE.Name AS DepartmentName
FROM
    Employees E
JOIN
    DepartmentCTE DCTE ON E.DepartmentID = DCTE.ID;

Differentiating and Use Cases

  • Temp Tables vs. Table-Valued Parameters
    • Use Temp Tables for temporary storage and processing during a session or batch.
    • Use Table-Valued Parameters when you need to pass structured data to stored procedures or functions.
  • Global Temp Tables
    • Use Global Temp Tables when you need temporary storage that persists across multiple sessions.
  • CTEs
    • Use CTEs for simplifying complex queries, improving readability, and avoiding the need for creating permanent views.

Conclusion

Understanding the use cases and syntax of Temp Tables, Table-Valued Parameters, Global Temp Tables, and CTEs is crucial for efficient database management. 

Whether you need temporary storage, structured parameter passing, persistent global storage, or query simplification, SQL Server provides a range of tools to meet your needs. Choosing the right tool for the job can greatly enhance the performance, scalability, and maintainability of your SQL Server solutions.

Happy querying!

Comments

Popular posts from this blog

Optional Parameters in C# — Writing Flexible and Clean Methods

Hello, .NET developers! 👋 How often have you created multiple method overloads just to handle slightly different cases? Maybe one method accepts two parameters, another three, and one more adds a flag for debugging? That’s a lot of code duplication for something that can be solved beautifully with optional parameters . Optional parameters in C# let you define default values for method arguments. When a caller doesn’t pass a value, the compiler automatically substitutes the default. This feature helps keep your APIs simple, readable, and maintainable. 🎥 Explore more on YouTube : DotNet Full Stack Dev Understanding Optional Parameters Optional parameters are defined by assigning default values in the method signature. When calling the method, you can omit those parameters if you’re okay with the defaults. Example public class Logger { public void Log(string message, string level = "INFO", bool writeToFile = false) ...

.NET 10: Your Ultimate Guide to the Coolest New Features (with Real-World Goodies!)

 Hey .NET warriors! 🤓 Are you ready to explore the latest and greatest features that .NET 10 and C# 14 bring to the table? Whether you're a seasoned developer or just starting out, this guide will show you how .NET 10 makes your apps faster, safer, and more productive — with real-world examples to boot! So grab your coffee ☕️ and let’s dive into the awesome . 💪 1️⃣ JIT Compiler Superpowers — Lightning-Fast Apps .NET 10 is all about speed . The Just-In-Time (JIT) compiler has been turbocharged with: Stack Allocation for Small Arrays 🗂️ Think fewer heap allocations, less garbage collection, and blazing-fast performance . Better Code Layout 🔥 Hot code paths are now smarter, meaning faster method calls and fewer CPU cache misses. 💡 Why you care: Your APIs, desktop apps, and services now respond quicker — giving users a snappy experience . 2️⃣ Say Hello to C# 14 — More Power in Your Syntax .NET 10 ships with C# 14 , and it’s packed with developer goodies: Field-Bac...

Implementing and Integrating RabbitMQ in .NET Core Application: Shopping Cart and Order API

RabbitMQ is a robust message broker that enables communication between services in a decoupled, reliable manner. In this guide, we’ll implement RabbitMQ in a .NET Core application to connect two microservices: Shopping Cart API (Producer) and Order API (Consumer). 1. Prerequisites Install RabbitMQ locally or on a server. Default Management UI: http://localhost:15672 Default Credentials: guest/guest Install the RabbitMQ.Client package for .NET: dotnet add package RabbitMQ.Client 2. Architecture Overview Shopping Cart API (Producer): Sends a message when a user places an order. RabbitMQ : Acts as the broker to hold the message. Order API (Consumer): Receives the message and processes the order. 3. RabbitMQ Producer: Shopping Cart API Step 1: Install RabbitMQ.Client Ensure the RabbitMQ client library is installed: dotnet add package RabbitMQ.Client Step 2: Create the Producer Service Add a RabbitMQProducer class to send messages. RabbitMQProducer.cs : using RabbitMQ.Client; usin...