Reputation: 1979
I have this query in SQL Server:
select column
from table_53;
Now, I want to get this 53 from another table, so what I want to do is something like this:
select column
from table_(select id from table2);
Is there any way to do this in SQL Server?
Upvotes: 0
Views: 118
Reputation: 12295
Yes, you can, but using something like this:
DECLARE @ID INT;
DECLARE @QUERY NVARCHAR(MAX);
SELECT @ID = ID FROM TABLE_2;
--IF @ID EQUALS 53 THEN
SET @QUERY = 'SELECT COLUMN FROM TABLE_' + CAST(@ID AS NVARCHAR(10));
-- @QUERY EQUALS TO 'SELECT COLUMN FROM TABLE_53'
EXEC (@QUERY);
Upvotes: 0
Reputation: 28196
This is definitely not the way SQL thinks and works. Maybe your suggested approach can be mimicked by way of writing stored procedures in which you create SQL-statements which are then evaluated. However, this will not be very efficient.
A better approach would be to store the values of all your individual separate tables into one master table and mark them in a separate column tblid
with their number (e.g. 53
). Then you can always filter them from this master table by looking for this tblid
.
Upvotes: 1
Reputation: 1689
You need dynamic sql query here.
declare @sqlQuery = 'select column
from table_(';
set @sqlQuery = @sqlQuery + 'select id from table2)';
EXEC (@sqlQuery)
Note :- One of cons of using dynamic sql query is sql injection. I would suggest to have better table structure or try to used parameterized query.
Upvotes: 0