An overview of the SQL table variable

An overview of the SQL table variable

An overview of the SQL table variable

SQLShack

SQL Server training Español

An overview of the SQL table variable

October 16, 2019 by Rajendra Gupta This article explores the SQL Table variables and their usage using different examples.

Introduction

We use many intermediate tables to perform data manipulation, computation, and data sorting from multiple sources. It is beneficial to use temporary tables instead of a regular table and drop them later. Usually, we define SQL temporary tables using the # symbol: 1234567 CREATE TABLE #temp(DBname VARCHAR(20));INSERT INTO #temp SELECT name FROM sys.sysdatabases;SELECT *FROM #temp;DROP TABLE #temp; A SQL temporary table uses following process. Define Use (Insert, update, delete, select) Drop In this article, we will look at an alternative way of storing temporary data, i.e. SQL table variables. Let’s take an overview of it along with multiple examples.

Overview of SQL table variables

The table variable is a special data type that can be used to store temporary data similar to a temporary table. The syntax for the table variable looks similar to defining a new table using the CREATE TABLE statement: 1234 DECLARE @Products TABLE(ProductID INT,ProductName VARCHAR(30)); In the above query, we specified a table variable using the DECLARE and TABLE keyword. The table variable name must start with the @ symbol. We also define table columns, data types, constraint similar to a regular table.

Scope of SQL table variable

The table variable scope is within the batch. We can define a table variable inside a stored procedure and function as well. In this case, the table variable scope is within the stored procedure and function. We cannot use it outside the scope of the batch, stored procedure or function.

Insert data into a table variable

We can insert data into a table variable similar to a regular table: 123456789 DECLARE @Products TABLE(ProductID INT, ProductName VARCHAR(30));INSERT INTO @ProductsVALUES(1, 'Carpet'); You can retrieve a record from a table variable using the Select statement: We cannot drop the table variable using the DROP Table statement. If you try to drop it, you get incorrect syntax message:
We do not require dropping the table variable. As mentioned earlier, the scope of the table variable is within the batch. The scope of it lasts at the end of the batch or procedure.

The storage location of SQL table variable

Let’s think of a few questions: What is the storage location of a table variable? Is it created in the source database in which we execute the script? Most people are confused about the table variable location and think that it is stored in memory. Let’s check it out. We can use sys.tables for listing tables in the tempdb database. Let’s execute the following query and do the following: Check the existing tables in tempdb Declare a table variable Check the tables in tempdb again 1234567891011 SELECT *FROM TEMPDB.sys.tables;GODECLARE @Products TABLE(ProductID INT, ProductName VARCHAR(30));GoSELECT *FROM TEMPDB.sys.tables;GO In the output, we did not get any existing table before and after declaring a table variable: Does it mean that the table variable is not stored in the tempdb database? No, it is not valid. You can note that we use Go statement after each step to finish the batch before starting the subsequent batch. Table variable scope finishes at the end of the batch, and SQL Server automatically drops it. Let’s run the following query. In the modified query, we removed the Go statement after declaring a table variable and checking the existence of it in the tempdb: 12345678910 SELECT *FROM TEMPDB.sys.tables;GODECLARE @Products TABLE(ProductID INT, ProductName VARCHAR(30));SELECT *FROM TEMPDB.sys.tables;GO Now, in the output, it shows the table variable in the tempdb database:

Table variable and explicit transaction

We cannot use the table variable in the explicit transaction, it does not return any error message, but it skips the transaction. In the following query, we execute the query in four steps: Declare a table variable Starts a transaction using the BEGIN TRAN statement Insert record into the table variable Rollback transaction using ROLLBACK TRAN Verify whether the record exists in the table variable or not. It should not exist because we performed rollback in step 4 12345678 DECLARE @TableVariableA TABLE(Name VARCHAR(30));BEGIN TRAN;INSERT INTO @TableVariableAVALUES('SQL Server');ROLLBACK TRAN;SELECT *FROM @TableVariableA;GO In the output, we can verify that ROLLBACK TRAN did not perform a rollback of data from the table variable: If we require explicit transactions, we can use the temporary tables. The explicit transaction works on temporary tables.

User-defined functions UDF and table variable

We can define and use table variables in the user-defined functions as well. Execute the following query: Define a user-defined function using CREATE FUNCTION Statement Define a table variable and define columns for it Define UDF activity in the BEGIN…END statement Return the variable value 12345678910 CREATE FUNCTION TableVariableWithinAFunction()RETURNS @TableVariable TABLE(Name VARCHAR(50))AS BEGIN INSERT INTO @TableVariable SELECT FirstName FROM [DemoSQL].[dbo].[Employee]; RETURN; END;GO Later, we can use a UDF function to retrieve the records: 1 Select * from TableVariableWithinAFunction() It retrieves the records from UDF: This example showed that we could use table variables in a user-defined function as well. We cannot use temporary tables inside a user-defined function.

Indexes and table variable

Table variables are a particular type of data types. We can use these table variables similar to the user table to hold temporary data. Q: Is it possible to add indexes on the table variables? A: No, we cannot define indexes on the table variables. Q: If we cannot define indexes on table variables, do we have any alternatives for it? A: Yes, indeed, we cannot define index in the table variables, but we can define primary and unique key constraints on the table variables: 12345 DECLARE @Customer TABLE(CustomerId INT PRIMARY KEY NONCLUSTERED, CustomerName NVARCHAR(30) UNIQUE CLUSTERED(CustomerName)); We cannot define an explicit clustered and non-clustered index on the table variable. Primary key and unique key constraints automatically create the internal indexes on it. You can use these constraints to unique define rows in an index as well. Can we modify a SQL table variable structure after declaration? A: No, we cannot alter a table variable definition after the declaration. Suppose you define a table variable for holding the Varchar data type of length 50. Later, our requirement changes, and we want to modify it for length 100. We cannot alter a table variable structure. We can define another table variable. We can also modify the definition of an existing table variable.

Conclusion

In this article, we explored the SQL table variables and their usage for storing temporary data. We also compared it with the temporary tables. Let’s have a quick summary of what we have learned: Temporary table SQL table variable Syntax We use the following format for defining a temporary table: Define Use Drop 12 CREATE TABLE #Employee (Id INT, Name VARCHAR(50)) We define a temporary table using the hash sign. In Table variable, we use the following format: Define Use We cannot drop a table variable using an explicit drop statement. Storage It is stored in the tempdb system database. The storage for the table variable is also in the tempdb database. Transactions We can use temporary tables in explicit transactions as well. Table variables cannot be used in explicit transactions. User-defined function We cannot use it in the user-defined functions. We can use table variables in the UDF. Indexes We can define explicit indexes on the temporary tables. We cannot define explicit indexes on table variables. We can use primary and unique key constraints. Scope Scope of a temporary table is local and global as defined while creating it. Scope of the table variable is within the batch. We cannot use it outside the batch. Author Recent Posts Rajendra GuptaHi! I am Rajendra Gupta, Database Specialist and Architect, helping organizations implement Microsoft SQL Server, Azure, Couchbase, AWS solutions fast and efficiently, fix related issues, and Performance Tuning with over 14 years of experience.

I am the author of the book "DP-300 Administering Relational Database on Microsoft Azure". I published more than 650 technical articles on MSSQLTips, SQLShack, Quest, CodingSight, and SeveralNines.

I am the creator of one of the biggest free online collections of articles on a single topic, with his 50-part series on SQL Server Always On Availability Groups.

Based on my contribution to the SQL Server community, I have been recognized as the prestigious Best Author of the Year continuously in 2019, 2020, and 2021 (2nd Rank) at SQLShack and the MSSQLTIPS champions award in 2020.

Personal Blog: https://www.dbblogger.com
I am always interested in new challenges so if you need consulting help, reach me at [email protected]

View all posts by Rajendra Gupta Latest posts by Rajendra Gupta (see all) Copy data from AWS RDS SQL Server to Azure SQL Database - October 21, 2022 Rename on-premises SQL Server database and Azure SQL database - October 18, 2022 SQL Commands to check current Date and Time (Timestamp) in SQL Server - October 7, 2022

Related posts

Overview of the Shrink TempDB database in SQL Server SQL varchar data type deep dive A complete guide to T-SQL Metadata Functions in SQL Server SQL Variables: Basics and usage The Table Variable in SQL Server 35,924 Views

Follow us

Popular

SQL Convert Date functions and formats SQL Variables: Basics and usage SQL PARTITION BY Clause overview Different ways to SQL delete duplicate rows from a SQL Table How to UPDATE from a SELECT statement in SQL Server SQL Server functions for converting a String to a Date SELECT INTO TEMP TABLE statement in SQL Server SQL WHILE loop with simple examples How to backup and restore MySQL databases using the mysqldump command CASE statement in SQL Overview of SQL RANK functions Understanding the SQL MERGE statement INSERT INTO SELECT statement overview and examples SQL multiple joins for beginners with examples Understanding the SQL Decimal data type DELETE CASCADE and UPDATE CASCADE in SQL Server foreign key SQL Not Equal Operator introduction and examples SQL CROSS JOIN with examples The Table Variable in SQL Server SQL Server table hints – WITH (NOLOCK) best practices

Trending

SQL Server Transaction Log Backup, Truncate and Shrink Operations Six different methods to copy tables between databases in SQL Server How to implement error handling in SQL Server Working with the SQL Server command line (sqlcmd) Methods to avoid the SQL divide by zero error Query optimization techniques in SQL Server: tips and tricks How to create and configure a linked server in SQL Server Management Studio SQL replace: How to replace ASCII special characters in SQL Server How to identify slow running queries in SQL Server SQL varchar data type deep dive How to implement array-like functionality in SQL Server All about locking in SQL Server SQL Server stored procedures for beginners Database table partitioning in SQL Server How to drop temp tables in SQL Server How to determine free space and file size for SQL Server databases Using PowerShell to split a string into an array KILL SPID command in SQL Server How to install SQL Server Express edition SQL Union overview, usage and examples

Solutions

Read a SQL Server transaction logSQL Server database auditing techniquesHow to recover SQL Server data from accidental UPDATE and DELETE operationsHow to quickly search for SQL database data and objectsSynchronize SQL Server databases in different remote sourcesRecover SQL data from a dropped table without backupsHow to restore specific table(s) from a SQL Server database backupRecover deleted SQL data from transaction logsHow to recover SQL Server data from accidental updates without backupsAutomatically compare and synchronize SQL Server dataOpen LDF file and view LDF file contentQuickly convert SQL code to language-specific client codeHow to recover a single table from a SQL Server database backupRecover data lost due to a TRUNCATE operation without backupsHow to recover SQL Server data from accidental DELETE, TRUNCATE and DROP operationsReverting your SQL Server database back to a specific point in timeHow to create SSIS package documentationMigrate a SQL Server database to a newer version of SQL ServerHow to restore a SQL Server database backup to an older version of SQL Server

Categories and tips

►Auditing and compliance (50) Auditing (40) Data classification (1) Data masking (9) Azure (295) Azure Data Studio (46) Backup and restore (108) ►Business Intelligence (482) Analysis Services (SSAS) (47) Biml (10) Data Mining (14) Data Quality Services (4) Data Tools (SSDT) (13) Data Warehouse (16) Excel (20) General (39) Integration Services (SSIS) (125) Master Data Services (6) OLAP cube (15) PowerBI (95) Reporting Services (SSRS) (67) Data science (21) ►Database design (233) Clustering (16) Common Table Expressions (CTE) (11) Concurrency (1) Constraints (8) Data types (11) FILESTREAM (22) General database design (104) Partitioning (13) Relationships and dependencies (12) Temporal tables (12) Views (16) ▼Database development (418) Comparison (4) Continuous delivery (CD) (5) Continuous integration (CI) (11) Development (146) Functions (106) Hyper-V (1) Search (10) Source Control (15) SQL unit testing (23) Stored procedures (34) String Concatenation (2) Synonyms (1) Team Explorer (2) Testing (35) Visual Studio (14) DBAtools (35) DevOps (23) DevSecOps (2) Documentation (22) ETL (76) ►Features (213) Adaptive query processing (11) Bulk insert (16) Database mail (10) DBCC (7) Experimentation Assistant (DEA) (3) High Availability (36) Query store (10) Replication (40) Transaction log (59) Transparent Data Encryption (TDE) (21) Importing, exporting (51) Installation, setup and configuration (121) Jobs (42) ▼Languages and coding (686) Cursors (9) DDL (9) DML (6) JSON (17) PowerShell (77) Python (37) R (16) SQL commands (196) SQLCMD (7) String functions (21) T-SQL (275) XML (15) Lists (12) Machine learning (37) Maintenance (99) Migration (50) Miscellaneous (1) ►Performance tuning (869) Alerting (8) Always On Availability Groups (82) Buffer Pool Extension (BPE) (9) Columnstore index (9) Deadlocks (16) Execution plans (125) In-Memory OLTP (22) Indexes (79) Latches (5) Locking (10) Monitoring (100) Performance (196) Performance counters (28) Performance Testing (9) Query analysis (121) Reports (20) SSAS monitoring (3) SSIS monitoring (10) SSRS monitoring (4) Wait types (11) ►Professional development (68) Professional development (27) Project management (9) SQL interview questions (32) Recovery (33) Security (84) Server management (24) SQL Azure (271) SQL Server Management Studio (SSMS) (90) SQL Server on Linux (21) ►SQL Server versions (177) SQL Server 2012 (6) SQL Server 2016 (63) SQL Server 2017 (49) SQL Server 2019 (57) SQL Server 2022 (2) ►Technologies (334) AWS (45) AWS RDS (56) Azure Cosmos DB (28) Containers (12) Docker (9) Graph database (13) Kerberos (2) Kubernetes (1) Linux (44) LocalDB (2) MySQL (49) Oracle (10) PolyBase (10) PostgreSQL (36) SharePoint (4) Ubuntu (13) Uncategorized (4) Utilities (21) Helpers and best practices BI performance counters SQL code smells rules SQL Server wait types © 2022 Quest Software Inc. ALL RIGHTS RESERVED. GDPR Terms of Use Privacy
Share:
0 comments

Comments (0)

Leave a Comment

Minimum 10 characters required

* All fields are required. Comments are moderated before appearing.

No comments yet. Be the first to comment!