It is possible?
DECLARE @vTableName varchar(50)
SET @vTableName = (SELECT TableName FROM qms_Types WHERE Id = 1)
SELECT * FROM @vTableName
<
I think you want this:
DECLARE @vTableName table(TableName varchar(50))
insert into @vTableName
SELECT TableName FROM qms_Types WHERE Id = 1
SELECT * FROM @vTableName
if you're trying to select from a table of that name, then you can do something like this:
DECLARE @vTableName varchar(50)
SET @vTableName = (SELECT TableName FROM qms_Types WHERE Id = 1)
EXECUTE('SELECT * FROM [' + @vTableName + ']')
Short answer: No.
Long answer: Noooooooooooooooooooooooooooooooooooooo. Use dynamic SQL if you have to, but if you're structuring your tables in a way where you don't know the table name ahead of time, it might benefit you to rethink your schema.
Here is a great resource for learning how to use dynamic SQL: The Curse and Blessings of Dynamic SQL
my solution for this:
EXECUTE('SELECT * FROM ' + TableName + '')
The only way you can do this is through Dynamic SQL which refers to the practice of creating a T-SQL text and executing it using the sp_executesql (or simply exec)
Here is a helpful link about dynamic sql The Curse and Blessings of Dynamic SQL.
You should really think whether or not this is a case for dynamic sql or if there is another way for you to perform this operation.
It seems as though different folks are interpreting the OP differently.
I'm pretty sure the OP is asking for this type of concept / ability / maneuver...
"Put a table name into a variable and then use that variable as though it were a table name."
DECLARE @TableIWantRecordsFrom varchar(50)
-- ^^^^^^^^^^^^^^^^^^^^^^
SET @TableIWantRecordsFrom = (SELECT TableName FROM qms_Types WHERE Id = 1) -- (L1)
-- ^^^^^^^^^^^^^^^^^^^^^^
-- Let's say, at this point, @TableIWantRecordsFrom ... contains the text 'Person'
-- ^^^^^^^^^^^^^^^^^^^^^^
-- assuming that is the case then...
-- these two queries are supposed to return the same results:
SELECT top 3 fname,lname,mi,department,floor FROM Person
-- ^^^^^^
SELECT top 3 fname,lname,mi,department,floor FROM @TableIWantRecordsFrom -- (L2)
-- ^^^^^^^^^^^^^^^^^^^^^^
From reading all the responses and answers, it appears that this kind of maneuver can't be done - unless - you use dynamic SQL which...
================================================================
There are other languages where this can be done... in literally, two lines of code (see (L1) and (L2) in above code) and not having to do a lot of formatting and editing.)
(I've done it before - there is another language where all you'd need is L1 and L2...)
================================================================
It is unfortunate that SQL Server will not do this without going to a decent amount of effort...