I want a program to access a table/view/stored procedure, etc. (something materialized, let’s call it X) that abstracts the real location of the data contained in three basic tables (the tables have the same definition in all locations).
I would want X to fetch the server name, catalog name and table name from somewhere (a table, probably) and access the specific three basic tables. The caller of X would not know which specific tables were being called.
How can I do this in SQL Server (2008)?
Like a function, a view can’t use dynamic SQL – it can’t go find some metadata reference somewhere and adjust accordingly.
I think the closest thing to what you want is a synonym. Let’s say you have three different databases,
A,BandC. InAthe table you want the view to reference isdbo.foo, inBit isdbo.bar, and inCit isdbo.splunge. So then you could create a synonym like so in each database:Now this technically isn’t a view, but in each database you can say…
…and it will return the data from the database-specific table.
To do this in a stored procedure would be much simpler. Say you store the server, database and table name in some table, e.g.
dbo.lookup:Now your program can say:
And your stored procedure can be:
I still don’t understand the point, and I don’t know what you’re planning to do when two different users expect to call your program at the same time, and they each should get results from a different location.