Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I use SQL Server table name in select query with a variable?

Tags:

People also ask

Can a table name be a variable in SQL Server?

Table variable is a type of local variable that used to store data temporarily, similar to the temp table in SQL Server. Tempdb database is used to store table variables. To declare a table variable, start the DECLARE statement. The name of table variable must start with at(@) sign.

Can I use variable in SELECT statement SQL?

Variables in SQL procedures are defined by using the DECLARE statement. Values can be assigned to variables using the SET statement or the SELECT INTO statement or as a default value when the variable is declared. Literals, expressions, the result of a query, and special register values can be assigned to variables.


Is this incorrect, can't we pass the table name to a select query dynamically?

This is giving me a error 'Must declare the table variable @TblName'

DECLARE @TblName VARCHAR(30)
SET @TblName = 'User'
SELECT * 
FROM @TblName