HiveBrain v1.2.0
Get Started
← Back to all entries
patternsqlModerate

SQL Server: Using 4 part identifiers when database may be on the same server

Submitted by: @import:stackexchange-dba··
0
Viewed 0 times
samethemaysqlpartdatabaseidentifiersusingwhenserver

Problem

In my client's setup, the database servers in lower environments are all on one server for cost saving purposes, but in higher environments, these databases are deployed on separate servers, and linked servers are used when queries run across the servers.

Example setup:

Dev:
  Server1: DB1, DB2
UAT: 
  Server1: DB1 (with linked server for DB2)
  Server2: DB2


I am trying to maintain the databases with a single set of SQL Server Data Tools projects, using 4 part [server].[database].[schema].[object] identifiers and database reference variables to model the relationships. This works well when the databases are not on the same server, but fails when the databases are on the same server.

My questions:

  • Is there a default way to refer to the local server in a 4 part identifier other than omitting the server definition?



  • If not, is there a way to add a linked server pointing to the local server?



  • If neither of the above is possible, is there another way to manage this in SQL Server?

Solution

Use a synonym, and just don't sync the synonyms. So when it is on a local server:

CREATE SYNONYM dbo.FooBar FOR DBName.dbo.TableName;


When it is remote:

CREATE SYNONYM dbo.FooBar FOR ServerName.DBName.dbo.TableName;


Now all your code just has to reference dbo.FooBar no matter where it is.

Code Snippets

CREATE SYNONYM dbo.FooBar FOR DBName.dbo.TableName;
CREATE SYNONYM dbo.FooBar FOR ServerName.DBName.dbo.TableName;

Context

StackExchange Database Administrators Q#74566, answer score: 11

Revisions (0)

No revisions yet.