Dynamic Table Name Variable in SQL Server
Last Updated :
28 Dec, 2023
In SQL Server, the dynamic table name variable is used when the name of the table is not explicitly stated in a query but is set in a variable and used instead. This can be in situations where the user does not know or the executing code does not know the table name beforehand and is only determined at run time.
Dynamic Table Variable Usage
The dynamic table variable can be used to get input from the user from the front-end at runtime or may be due to some choice from user action. By this method, the user can get data from different tables to display data in the front end based on some criteria. So the front end can send the table name dynamically from a text-box input to back-end to fetch data from different tables based on user input. There can also be other use cases for using a dynamic table name at run time.
We can create stored procedures that accept the table name as a parameter to accept different table names at run time to make the same procedure re-usable for different tables.
There can also be some situations where tables are created dynamically and data inserted at run time. Here also we can use the dynamic table name variable to handle these situations.
Examples: Dynamic Table Variable Usage
Example 1
The below example shows a very simple dynamic SQL with a table variable to get data:
Example of Dynamic Table variable using dynamic SQL.
DECLARE @tableName1 NVARCHAR(50) = 'Students';
DECLARE @SQLString NVARCHAR(2000);
SET @SQLString = N'SELECT * FROM ' + QUOTENAME(@tableName1);
EXECUTE sp_executesql @SQLString;
In the above example the '@tableName1' is used a table variable to the select statement to get table data.
Example 2
The below example shows how to use a stored procedure to get table data using parameters for table name:
Create Procedure GetDynamicTableData
(
@TableName varchar(30)
)
As
Begin
Declare @SQLString nvarchar(1000)
Set @SQLString='Select * from ' + QUOTENAME(@TableName)
EXEC sp_executesql @SQLString
End
The @TableName variable is used in this stored procedure 'GetDynamicTableData' to send the table name to select statement.
Below is how the stored procedure is called with the table name.
EXEC GetDynamicTableData 'DynamicTab2'
Example 3
Below example shows about, how we can create a dynamic table using the table variable:
Create Procedure AddNewTable
(
@TableName varchar(30),
@ColumnName1 varchar(30),
@ColumnName2 varchar(30),
@ColumnName3 varchar(30)
)
As
Begin
Declare @SQLString nvarchar(1000)
Set @SQLString='Create Table ' + QUOTENAME(@TableName) + '(' + QUOTENAME(@ColumnName1) +
'varchar(50),' + QUOTENAME(@ColumnName2) + 'varchar(50),' + QUOTENAME(@ColumnName3) + 'varchar(50))'
EXEC sp_executesql @SQLString
End
The @TableName is the variable name to pass the new table name to 'AddNewTable' stored procedure to create the new table dynamically at run time.
When we execute the below stored procedure the new table is created.
EXEC AddNewTable 'DynamicTab2','Column1','Column2','Column3'
Security Considerations
While using dynamic table names the security aspect like SQL Injection should be taken care. So always the table name in the dynamic SQL should be used with the 'QUOTENAME' like QUOTENAME(@TblName) so that no malicious command is executed and only a valid table name is used with the table variable.
Conclusion
The dynamic Table Name variable is a good method to handle table names dynamically and offers great flexibility. At the same time using dynamic table name can make the code less readable and difficulty to maintain, and so document your code in detail to make it understandable by others. Also, the dynamic table usage can lead to security issues and so care should be taken for security with proper validation.
Similar Reads
Dynamic SQL in SQL Server
In SQL Server, at times the SQL Queries need to be dynamic and not static, meaning the complete SQL query may be built dynamically at run time as a string using the user inputs and any specific application logic. This can be done in queries run from back-end applications or inside stored procedures.
6 min read
Dynamic SQL and Temporary Tables in SQL Server
In SQL Server, creating and using Temp Tables using dynamic SQL is a good feature when we need to temporarily create tables at run time and delete automatically all within a session. They can be very useful when we need to store temporary data in a structured format and do data manipulation using Da
6 min read
How to Declare a Variable in SQL Server?
In SQL Server, variables play a critical role in the dynamic execution of SQL scripts and procedures. Variables allow you to store and manipulate data temporarily within the scope of a batch or procedure. By using the DECLARE statement, you can create variables with specific data types, which can th
6 min read
SQL Server SELECT INTO @Variable
In the world of SQL Server, the SELECT INTO statement is a powerful syntax for retrieving data from one or more tables and inserting it into a new table. However, what if you want to store the result set of a SELECT query into a variable rather than a table? This is where the SELECT INTO @Variable s
6 min read
SQL Server Describe Table
SQL Server is a widely used Relational Database Management System (RDBMS) that allows users to create and manage databases effectively. When working with databases in SQL Server it is essential to understand the schema of the tables present in the database. Describing a table means getting informati
4 min read
How to Use Dynamic Variable Names in JavaScript?
Dynamic variable names are variable names that are not predefined but are generated dynamically during the execution of a program. This means the name of a variable can be determined at runtime, rather than being explicitly written in the code.Here are different ways to use dynamic variables in Java
2 min read
CREATE TABLE in SQL Server
SQL Server provides a variety of data management tools such as querying, indexing, and transaction processing. It supports multiple programming languages and platforms, making it a versatile RDBMS for various applications. With its robust features and reliability, SQL Server is a popular choice for
4 min read
VARCHAR, VARCHAR(MAX), and NVARCHAR in MS SQL Server
In SQL Server, VARCHAR, VARCHAR(MAX) and NVARCHAR are used to store variable-length text data. VARCHAR is efficient for non-Unicode text up to 8,000 characters, while VARCHAR(MAX) handling larger text data up to 2 GB. NVARCHAR supports Unicode data, making it suitable for multilingual applications.
3 min read
Select into and temporary tables in MS SQL Server
In SQL Server, the SELECT INTO TEMP TABLE statement is used to select data from one or more source tables and insert it into a temporary table. Temporary tables are extremely useful when dealing with intermediate results, or when working with subsets of data within a session without modifying or aff
4 min read
R Variables - Creating, Naming and Using Variables in R
A variable is a memory allocated for the storage of specific data and the name associated with the variable is used to work around this reserved block. The name given to a variable is known as its variable name. Usually a single variable stores only the data belonging to a certain data type. The na
6 min read