Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to form a table name from concatenating strings in Select Statement in SQL 2012

Tags:

sql

sql-server

I want to achieve this -

SELECT * FROM A1234

I have the the ID 1234 saved in another table called Aliases which has two columns Alias,ID with one record like this.

Alias = TestTable, ID = 1234

So I am trying something like this

SELECT * FROM ('A'+ (SELECT ID FROM Aliases WHERE Alias = 'TestTable'))

Any help would be appreciated

like image 673
user2869233 Avatar asked Nov 12 '13 20:11

user2869233


1 Answers

You should use dynamic sql.

DECLARE @Q VARCHAR(MAX),@ID INT
SET @ID=(Select DISTINCT ID from Aliases where Alias = 'TestTable') -- CHECK TO RETURN JUST ON RESULT
SET @Q='SELECT * FROM A'+CAST(@ID AS VARCHAR(10))
EXEC(@Q)
like image 78
Amir Keshavarz Avatar answered Oct 02 '22 10:10

Amir Keshavarz