SQL Server Synonym
An alias or alternative names can be given to any of the database objects like a table, view, stored procedure, user-defined function, and sequence with the help of SQL Server Synonym.
Whenever we create a SQL Server Synonym in a database, the synonym is referenced to a particular database object and that database object is called base object. The location of the base object to which the synonym is referenced can be either in the same database or in some other database in the same server or even on some other instance running on another server.
We can use SQL Server Synonym in various scenarios and take advantage out of them. Some of the scenarios are:
The syntax for creating a Synonym in SQL Server Database is:
In the above-written syntax:
How to use Synonym in SQL Server Database?
Let us understand SQL Server Synonym with the help of an example. Let us create a database and select that particular database. The syntax for creating and selecting that database is:
As we can see in the image a database by the name of 'salesdb' has been created and selected successfully.
Now, we will create a schema and a table inside that schema. The syntax for the creation of a schema and a table is:
As we can see in the image a schema named 'grocery' has been created successfully and a table named fruits having two columns to store the quantity and name of the fruits inside the grocery schema is also created successfully.
Now let us add some data to the fruits table. The syntax for the same is:
As shown in the image the seven rows of data have been inserted into the fruits table. And the same can be seen as the output of the SELECT command.
Whenever we want to refer to the fruits table, first we need to write the database name followed by the schema name and then the name of the table. To reduce this overhead, we can create a synonym with the syntax:
The synonym named 'fruits' has been created successfully and now we can use it.
So, this article helps us to understand the working of the Synonym in SQL Server and how to use it according to our problem requirement.