1

We are developing a database that consolidates few SQL Server DBs for a reporting requirement. Each DB has a number of views. No direct table or SP objects require to be accessible. All DBs and the new DB sitting in the same server. So we can develop cross-database queries quite easily with the Fully qualified object names.

i.e SELECT * FROM [SERVER].[DATABASE].[Schema].[View]

The problem is the depending database names differ between dev/ staging/ production environments of depending databases.

We have investigated the Synonym approach for the individual views and working fine. The advice we trying to seek from someone expert here is what is the best practice we should adhere to creating a single point to maintain this database alias instead of creating synonyms for each view so that we could do this once per environment and can maintain new queries same across different environments.

Randi Ratnayake
  • 674
  • 9
  • 23
  • https://stackoverflow.com/questions/6555646/sql-server-cross-database-alias – Daniel E. Jan 22 '19 at 10:48
  • @DanielE. still refers to the synonym option we have sought and doesn't resolve the issue of having to hardcode the database name. – Randi Ratnayake Jan 22 '19 at 11:03
  • i am thinking you can have a table where you can store db/server/view names against a common identifier. later at the beginning of your query you could set a variable with correct value by doing a select command. and then make your query a prepared statement/string (@SqlStatement) where you can concatenate table/view/db/server name from respective variables and finally you will need to use EXEC sp_executeSQL @SqlStatement. This means you will have a list of objects in a table as a string and you can use it across all env or make it env specific. Sorry for the essay – Sabbir Hassan Jan 22 '19 at 14:05
  • Do you use sql server database projects and have CI/CD pipelines for your databases? It's some work to setup, but then you specify that in your queries like `$(database_name)` and the deploy stage figures it out. – Jason Goemaat May 02 '23 at 14:12
  • @JasonGoemaat Thank you. Yes I ended up doing that. This is a very long time ago. – Randi Ratnayake May 03 '23 at 22:12

0 Answers0