Note: This is for SQL Server 2008.
I have a table that contains a number of columns, two of which are relevant to this discussion: Object and TableID. Object is a readable name. TableID corresponds to the table associated with Object, albeit the associated tables all begin with the letter T, as in table T135 or table T143.
SchemaTable
Object TableID /* Object is type varchar, TableID is type int
Form1 135
Form2 143
Form3 321
I want to craft a SQL query which will select contents from these tables, based on the value of Object. Here's what I have so far (which doesn't work):
SELECT Col1, Col2
FROM (
SELECT (T' + CAST(TableID AS VARCHAR))
FROM SchemaTable
WHERE Object = 'Form1'
)Tbl_T
WHERE Col1 IS NOT NULL
Can I use a subquery to select the table in this manner? If not, what else do you suggest and how?
Thank you very much for any help.
Edit
It seems that my question or query is not clear. Let me try to fix that.
I could select, say, table T135 directly like this:
SELECT Col1, Col2
FROM T135
WHERE Col1 IS NOT NULL
But what I want to do is select Table T135, based on the column Object in table SchemaTable.
You see? I don't want to select a subtable of values from table SchemaTable. I just want to grab the TableID (i.e. 135) and select content from said table (i.e. T135). There is no TableID column in table T135. TableID effectively corresponds to the name of the table. It's not used as a key or identity into other tables. I think that's where the confusion lies in understanding what I seek to accomplish.
I hope that is more clearer.
Thank you for your help.