Coding Schools


 
Python | C Sharp | Azure AI | HTML | JavaScript | CSS | SQL Server
Normalization in SQL Server
DDL and DML in SQL Server
SQL Server System Databases
SQL Server System Tables
Joins in SQL Server
SQL Server - Indexes
CTE in SQL Server
SQL Server - Locks
Optimization Techniques in SQL Server
How to Setup NDF Files in SQL Server
Deadlocks in SQL Server
Transactions in SQL Server
Difference UDF vs Stored Procedure
SQL Server Triggers
SQL Server Isolation Levels
SQL Server Pivot Tables
SQL Server - Group By Statement
SQL Server - Find Second highest Number Query
SQL Server - Recursion in User Defined Function
SQL Server Error Handling
Difference Table Variable and Temporary Table
SQL Server - Temporal Tables
User Defined Functions - SQL Server
Stored Procedures - SQL Server

Difference Table Variable and Temporary Table



Table variables and temporary tables are both used to store temporary data in SQL Server, but they have some differences in terms of scope, performance, and usage. Here's a comparison:

Table Variables

  1. Declaration: Declared using the DECLARE statement.

    sql
    DECLARE @TempTable TABLE (
        Column1 INT,
        Column2 VARCHAR(50)
    );
    
  2. Scope: Limited to the batch, stored procedure, or function in which they are declared. They are automatically dropped when the batch or procedure ends.

  3. Transaction Behavior: Not affected by transaction rollbacks. If a transaction is rolled back, the table variable retains its data.

  4. Indexing: Limited indexing options. Only primary keys and unique constraints can be applied. No support for non-clustered indexes.

  5. Performance: Generally faster for small datasets due to fewer logging operations. However, performance can degrade with larger datasets.

  6. Statistics: Limited support for statistics, which can lead to less optimal execution plans.

  7. Usage: Suitable for small to moderate-sized datasets and scenarios where the scope is limited to a single batch or procedure.

Temporary Tables

  1. Declaration: Created using the CREATE TABLE or SELECT INTO statements with a prefix # (local) or ## (global).

    sql
    CREATE TABLE #TempTable (
        Column1 INT,
        Column2 VARCHAR(50)
    );
    
    -- Or
    SELECT Column1, Column2
    INTO #TempTable
    FROM SourceTable;
    
  2. Scope: Local temporary tables (#TempTable) are limited to the session that created them. Global temporary tables (##TempTable) are accessible by all sessions but are dropped when the session that created them ends and no other session is using them.

  3. Transaction Behavior: Affected by transaction rollbacks. If a transaction is rolled back, the changes to the temporary table are also rolled back.

  4. Indexing: Support for primary keys, unique constraints, and non-clustered indexes. You can create indexes explicitly using the CREATE INDEX statement.

  5. Performance: Generally better performance for larger datasets due to support for indexing and statistics. Temporary tables use the tempdb database.

  6. Statistics: Full support for statistics, leading to better query optimization.

  7. Usage: Suitable for larger datasets and scenarios where temporary data needs to be accessed across multiple batches or sessions.

Summary Table

Here's a quick comparison of key differences:

FeatureTable VariablesTemporary Tables
DeclarationDECLARE statementCREATE TABLE or SELECT INTO
ScopeBatch, stored procedure, functionSession (local), Global
Transaction BehaviorNot affected by rollbacksAffected by rollbacks
IndexingLimited (PK, unique constraints)Full support (PK, unique, non-clustered)
PerformanceFaster for small datasetsBetter for larger datasets
StatisticsLimitedFull support
UsageSmall to moderate-sized datasetsLarger datasets, multi-batch scenarios

Both table variables and temporary tables are useful tools, and the choice between them depends on the specific requirements of your task. If you have any specific use cases or need further details, feel free to let me know!




All rights reserved | Privacy Policy | Sitemap