question

Purring avatar image
Purring asked

Get the Actual object (such as a table) in SQL Server?

I want to get the actual object - not the information about it in sys.objects. It would be really great if I could get a table based on its ID, assign it to a table variable, and then use that in a query instead of having to use dynamic sql. Why, you ask? The silly database I am working with has tables with names ending in a four digit year. I want to be able to pass a parameter to get the table to query. I searched high and low for this capability so maybe it's not possible but hoping it is... Any other suggestions would be greatly appreciated.
sql-serverdynamic-sqlobjects
1 comment
10 |1200

Up to 2 attachments (including images) can be used with a maximum of 512.0 KiB each and 1.0 MiB total.

KenJ avatar image KenJ commented ·
Out of curiosity, why would you know the object_id but not the name?
0 Likes 0 ·

1 Answer

·
KenJ avatar image
KenJ answered
If the only difference between the tables is the year in its name, you could use Partitioned Views ([ http://technet.microsoft.com/en-us/library/ms190019(v=sql.105).aspx][1]) or, a bit more involved, combine the tables into a single partitioned table ([ http://technet.microsoft.com/en-us/library/ms190787.aspx][2]). With a partitioned view or table you won't have to know a special table name, you just filter the results by the year you are looking for. Outside of that, you may be stuck with the dynamic SQL approach. [1]: http://technet.microsoft.com/en-us/library/ms190019(v=sql.105).aspx [2]: http://technet.microsoft.com/en-us/library/ms190787.aspx
3 comments
10 |1200

Up to 2 attachments (including images) can be used with a maximum of 512.0 KiB each and 1.0 MiB total.

Purring avatar image Purring commented ·
Thanks for the suggestions. I know the name but it's a string - not the actual table.
0 Likes 0 ·
Jeff Moden avatar image Jeff Moden commented ·
"I know the name but it's a string - not the actual table" So, you didn't actually look into partitioned views or the dynamic SQL approach?
0 Likes 0 ·
Purring avatar image Purring commented ·
Yes. Using the partitioned view made more sense in my case so went with that.
0 Likes 0 ·

Write an Answer

Hint: Notify or tag a user in this post by typing @username.

Up to 2 attachments (including images) can be used with a maximum of 512.0 KiB each and 1.0 MiB total.