Is there a difference between t-sql linked server and a synonym? If so what are they, and in which cases would I choose one over the other?
Yes, synonyms can be used with linked server, but the need to be defined on the calling (I'm guessng you'd call it 'Primary') server...
Linked Servers are a method by which a SQL Server can talk to another ODBC compliant database, such as another SQL Server instance or an Oracle database, with a direct T-SQL query. There are several important settings to know when setting up a Linked Server.
A synonym is a database object that serves the following purposes: Provides an alternative name for another database object, referred to as the base object, that can exist on a local or remote server.
View is logical and does not occupies space. Synonym can be created for single table, view, sequence or index. Synonym is physical and needs space.
Linked Servers and Synonyms are used for different purposes in SQL Server. One is not a substitute for another.
Linked Server is a way of establishing a connection to an external data source which could be another SQL Server, Oracle or any other type of data that has an OLE DB provider. More info here.
Synonyms are way of creating alias for database objects so as to simplify names in SQL queries and to provide a layer of abstraction to reduce impact on client queries when referenced object changes name or location. More info here.
Let us say you are on SQL Server ABC
and would like to create a stored procedure that needs to access ProductCategory
table in Adventureworks
database on SQL Server XYZ
.
XYZ
You can now access the table as follows
SELECT * FROM XYZ.dbo.Adventureworks.ProductCategory;
Note: You can use the above 4-part name in your queries and stored procedures to access not just 'ProductCategory' but any other tables and views.
Instead, you could create a synonym that references above remote database object and it can have short name, say ProductCategoryRemote
and then use it in your queries as
SELECT * FROM ProductCategoryRemote;
If you decide to use a different table or server (like when moving from UAT to PROD environments), all you need to do is drop and recreate the synonym referencing the new object.
Note: Synonym can reference objects within the same database, other databases on the same server or another server through linked server as in this example.
In conclusion, Linked Server are required to access an external data source and synonyms are used to create alias for database objects.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With