Dynamic Table Name Variable in SQL Server Last Updated : 28 Dec, 2023 Comments Improve Suggest changes Like Article Like Report 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 UsageThe 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 UsageExample 1The 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 2The below example shows how to use a stored procedure to get table data using parameters for table name: Create Procedure GetDynamicTableData(@TableName varchar(30))AsBeginDeclare @SQLString nvarchar(1000)Set @SQLString='Select * from ' + QUOTENAME(@TableName)EXEC sp_executesql @SQLStringEndThe @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 3Below 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 BeginDeclare @SQLString nvarchar(1000)Set @SQLString='Create Table ' + QUOTENAME(@TableName) + '(' + QUOTENAME(@ColumnName1) + 'varchar(50),' + QUOTENAME(@ColumnName2) + 'varchar(50),' + QUOTENAME(@ColumnName3) + 'varchar(50))'EXEC sp_executesql @SQLStringEndThe @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 ConsiderationsWhile 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. ConclusionThe 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. Comment More infoAdvertise with us J johnsupakin Follow Improve Article Tags : Geeks Premier League SQL Server Databases Geeks Premier League 2023 Similar Reads SQL Server BasicsIntroduction of MS SQL ServerData is a collection of facts and figures and we have humungous data available to the users via the internet and other sources. To manipulate the data, Structured Query Language (SQL) in short has been introduced years ago. There are different versions of SQL available in the market provided by diff2 min readCreate Database in MS SQL ServerDatabases in Microsoft SQL Server are crucial for managing data, categorized into system databases, which are auto-created and user databases, created by users. In this article, We will learn about the basics of system and user databases along with methods for creating and managing them using T-SQL5 min readList All Databases in SQL ServerIn SQL Server, databases are crucial for storing and managing data efficiently. Whether we are managing a large enterprise system or a small application, understanding how to list all the databases on our SQL Server is essential. In this article, we will write SQL queries that help us to retrieve al3 min readSQL Data TypesIn SQL, each column must be assigned a data type that defines the kind of data it can store, such as integers, dates, text, or binary values. Choosing the correct data type is crucial for data integrity, query performance and efficient indexing.Benefits of using the right data type:Memory-efficient3 min readSQL Server Tables & SchemasCREATE TABLE in SQL ServerSQL 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 for4 min readSQL Server Table VariableSQL Server Table variable is a local variable that stores data temporarily, similar to the temporary table in SQL Server. Tempdb database is used to store table variables. How to Declare Table Variable in SQL ServerTo declare a table variable in SQL Server, start the DECLARE statement. The name of t2 min readSQL Server DROP TABLEIn SQL Server, the DROP TABLE statement is used to remove or delete permanently from the database. In SQL Server after performing the DROP Operation we cannot revoke the table or database again, because it is an irreversible action. The Drop Operation is different from the DELETE Command, In the DEL3 min readRename Column in SQL ServerSQL Server is a widely used Relational Database Management System (RDBMS) that allows users to create and manage databases effectively. Renaming a column in a database is a common task usually required when users want to change the database schema. In this article, we will explore different methods3 min readSQL Server Rename TableIn SQL Server, renaming tables is a frequent operation that we often require during database maintenance or schema changes. This article ensures your seamless transition through the table-renaming process without compromising data integrity. it provides comprehensive guidance and guarantees protecti3 min readCREATE SCHEMA in SQL ServerA schema is a collection of database objects like tables, triggers, stored procedures, etc. A schema is connected with a user which is known as the schema owner. The database may have one or more schema. To create a schema in SQL Server use the 'CREATE SCHEMA' Statement. SQL CREATE SCHEMACREATE SCHE2 min readSQL Server Queries & OperationsSelect Statement in MS SQL ServerThe SELECT statement in SQL Server is a foundational SQL command used for querying and retrieving data from one or more tables within a database. This command allows users to specify which columns and rows to retrieve and apply filters to focus on specific data and perform various operations to mani4 min readInsert Statement in MS SQL ServerThe SQL Server INSERT statement is a fundamental command used to add new rows of data to a table. Whether we are inserting specific values, utilizing default values or copying data from another table.In this guide, weâll explore various ways to use the Insert statement in MS SQL Server with the help4 min readSQL Server UPDATESQL Server is a database engine. It works on the relational database management system (RDBMS) that allow programmer to create, manage, and manipulate data present on the relational database through their commands which is easy to learn and implement. UPDATE CommandThe UPDATE operation is a part of3 min readDELETE Statement in MS SQL ServerThe DELETE statement in MS SQL Server deletes specified records from the table. SyntaxMS SQL Server DELETE statement syntax is: DELETE FROM table_name WHERE condition; Note: Always use the DELETE statement with WHERE clause. The WHERE clause specifies which record(s) need to be deleted. If you exclu1 min readSQL Server SubqueryIn SQL Server, Subqueries are a powerful feature used to perform complex queries and combine data from multiple tables or multiple data sets. Subqueries can be used in different business cases and in different scenarios to join data from an inner query with an outer query. In this article let us see5 min readJoins in MS SQL ServerA database comprises tables and each table in case of RDBMS is called a relation. Let us consider a sample database named University and it has two tables named Student and Marks. If a user wants to transfer a certain set of rows, insert into select statement is used along with the query. But if a u2 min readRollup in SQL ServerThe ROLLUP operator enhances the capabilities of the GROUP BY clause by enabling the computation of subtotals and grand totals for a set of columns. It produces a result set that incorporates rows at various levels of aggregation. ROLLUP streamlines the aggregation process by eliminating the need fo4 min readSQL Server PIVOTSQL Server relational database management system. It has core functions that create, manipulate, and store data very efficiently. SQL Server contains all these characteristics and it has an extremely user-friendly installation interface, unlike other database servers that require extensive command-l7 min readSQL Server Constraints & KeysSQL PRIMARY KEY ConstraintThe PRIMARY KEY constraint in SQL is one of the most important constraints used to ensure data integrity in a database table. A primary key uniquely identifies each record in a table, preventing duplicate or NULL values in the specified column(s). Understanding how to properly implement and use the5 min readForeign key in MS SQL ServerA foreign key in SQL Server plays a crucial role in establishing and enforcing relationships between tables. It is a column or a set of columns in a table that references the primary key or a unique key in another table. By using foreign key constraints the SQL Server keeps data consistent between r6 min readCascading Referential Integrity Constraints in SQL Server Management StudioIn the Microsoft SQL server if we want to delete any record or column from one table but that record or column is a foreign key for another table then we will get the error to solve this problem we use Cascading referential integrity constraint. It allows the actions that SQL Server should take when4 min readHow to Turn IDENTITY_INSERT On and Off Using SQL Server?IDENTITY_INSERT in SQL Server is a valuable tool in SQL Server 2008, allowing us to control how identity values are assigned when inserting new records into a table. IDENTITY_INSERT ON is a Transact-SQL statement that allows us to explicitly specify the value we want to insert into the identity colu6 min readCan a Foreign Key be NUll in SQL Server?In SQL Server, foreign keys are essential to maintaining relationships between tables and enforcing referential integrity. A foreign key is a column (or set of columns) in a child table that references a primary key in a parent table and ensures that the data in both tables remains consistent. Howev4 min readSQL Server Indexes & PerformanceSQL IndexesAn index in SQL is a schema object that improves the speed of data retrieval operations on a table. Imagine them like an index in a book instead of flipping through every page (row), the database can jump right to the data it requires.Works by creating a separate data structure that provides pointer6 min readSQL Server CHARINDEX() functionCHARINDEX() function in SQL Server returns the position of a substring within a given string. The search performed in this function is case-insensitive. SyntaxCHARINDEX function syntax is: CHARINDEX(substring, string, [starting_position] ParametersCHARINDEX function accepts 3 parameters: substring:2 min readSQL Server SUBSTRING() FunctionThe SQL Server SUBSTRING function extracts a substring from a string, starting at a specified position and with an optional length. The SUBSTRING function also works in Azure SQL Database, Azure SQL Data Warehouse, and Parallel Data Warehouse. SyntaxThe SQL SUBSTRING function syntax is: SUBSTRING(in3 min readSQL Query OptimizationsPoorly written SQL queries can result in slow performance, high resource costs, locking and blocking issues, and unhappy users. The following are common practices that can be used to write efficient queries.1. Use Indexes WiselyIndexes let the database quickly look up rows instead of scanning the en6 min readHigh Availability (HA) in SQL ServerIt is the solution or process or technology to make the service or application or database availability 24x7 and 100% through needless and fault-tolerant components at the same location under either planned or unplanned outages. There are mainly five options in MS SQL Server to setup high availabili5 min readSQL Server Advanced TopicsDateTime2 vs DateTime in SQL ServerIn SQL Server, managing date and time values for various applications ranging from transaction processing to reporting. SQL Server offers two main data types for handling date and time:DateTimeDateTime2While both serve similar purposes, they differ significantly in terms of precision, storage requir3 min readDifference Between DateTime and SmallDateTime in SQL ServerSQL Server datatypes are used to store date and date and time values in the database, there are various types of date data types available in the SQL. Whenever we manage data in the SQL server database, itâs often very important to choose the right to store the date and time. The following two data3 min readFind Referencing Entities in SQL ServerUnderstanding the relationship between different object entities is very crucial in complex databases because changes in any object can affect the overall database. The SQL Server provides a very effective dynamic management function known as sys.dm_sql_referencing_entities which helps the user to t9 min readExport SQL Server Data From Table to CSV FileSQL Server is a very popular relational database because of its versatility in exporting data in Excel, CSV, and JSON formats. This feature helps with the portability of data across multiple databases. Here, we will learn how to export SQL Server Data from a table to a CSV file. Tools like Azure Dat3 min readHow to Setup Compatibility in Microsoft SQL Server?In SQL Server, managing the compatibility level of a database is crucial for ensuring that your database operates with the appropriate features and behaviors for your application. Compatibility levels allow us to use features and syntax from specific versions of SQL Server while running your databas4 min read Like