I have many DB in my SQL server, sometimes we put a copy of the QA DB server for test purposes, then I want to have a variable that select a value from a Table that indicates the name of the DB and change in my function, with no need of rewriting the function for changing the name of the DB, or executing a string to do this. How can I do this?
1 Answer
CREATE SYNONYM Cust FOR DB1.dbo.Customer
GO
SELECT * FROM Cust
GO
DROP SYNONYM Cust
CREATE SYNONYM Cust FOR DB2.dbo.Customer
GO
SELECT * FROM Cust
This technique has limitations, but in some cases it is very useful: MSDN CREATE SYNONYM
6 Comments
valverij
This is neat, I didn't know you could do this. Won't this only work if the two databases are on the same server, though? Or does it also work for linked servers?
Artemination
Is a good idea, but my DB has a lot of tables, it could work for some cases, but I'm trying to find a generic solution. (Let me read you link)
AlexK
Did you read my link? Remote or locale object: ` EXEC sp_addlinkedserver Server_Remote; GO USE tempdb; GO CREATE SYNONYM MyEmployee FOR Server_Remote.AdventureWorks2012.HumanResources.Employee; GO`
Artemination
This could work, I just need a Strategy in the Department to switch beetween DB, and the best is that it will be invisible for the programmers.
Aaron Bertrand
It won't be invisible to the programmers. If you want one programmer to see Cust as DB1.dbo.Customer, and another to see Cust as DB2.dbo.Customer, how do you propose you do that at the same time? A synonym can only point to one object at a time, so it may work when you're the only developer, but beyond that you're out of luck...
|
SELECT * FROM [QAServer].[QADatabase].[dbo].[MyTable]. If you're not careful, though, this can cause poor performance (or security holes, in some cases)