tags:

views:

52

answers:

2

Hi,

I was wondering if there is a way of querying in MSSQL Server (2005 or 2008 or both) using table names / columns that are stored within a table themselves. Hopefully this makes sense but I imagine not so below is an example of what i mean, consider the tables:

tableCollection
----------------------------
CollectionID        ident pk
Name                varchar(30)
CollectionTypeID    int fk

tableCollectionType
---------------------------
CollectionTypeID    ident pk
Name                varchar(30)
TableName           varchar(50)
NameColumn          varchar(50)

tableCollectionLinks
---------------------------
CollectionLinkID    ident pk
CollectionID        int
LinkID              int

This is obviously a simplistic example and the data types are only there to help to show an idea of the structure (so no wasted comments on db design please!).

What I want to achieve is to be able to select the links for a collection and then using the 'TableName' and 'NameColumn' in the table 'tableCollectionType' query across the relevant tables in order to achieve a listing in 1 query rather than two (using the values returned).

An idea of the query is below:

SELECT cl.LinkID, c.Name, ct.Name, 
(
      SELECT ***THE OBJECT NAME USING 'TableName' and 'NameColumn'
) As ObjectName
FROM tableCollectionLinks cl
INNER JOIN tableCollectionType c ON cl.CollectionID=c.CollectionID
INNER JOIN tableCollectionType ct ON ct.CollectionTypeID=c.CollectionTypeID
WHERE c.CollectionID=1

Any ideas?

Thanks, Steve

A: 

no there's no such thing. you could use dynamic sql for this but there's really no point in doing so.

Mladen Prajdic
I can believe you, what a shame. I'll leave the question open for a bit to see if anyone else has any differing view. reflection for sql.. now that would be good.
reflection for sql is in the form of information_schema views. you can use those with dynamic sql to get what you need but that's not really a good idea.
Mladen Prajdic
Thanks Mladen, i'll stick to 2 queries!
A: 

Take a look at the sys.tables, Sys.columns, sys.types system views.

From these 3 you might be able to see how to select the information you want.

MattC