0

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.

3
  • You must use dynamic query. Commented May 9, 2014 at 19:55
  • can you add your expected results? Commented May 9, 2014 at 20:17
  • Thank you, Hamlet. I think that will do the trick. Commented May 9, 2014 at 20:47

1 Answer 1

2

Yes you can use a subquery to select a table in this manner. here's another example :

select * from  
(select ndc,client_id,pkg_sz from ABC where pkg_sz=100) dist,  
(select ndc,client_id from XYZ where pkg_sz=500) trns  
where trns.client_id = dist.client_id  
and dist.ndc=trns.ndc;
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.