Thursday, September 25, 2008

Synonyms

SQL Server 2005's synonyms allow you to give an alias to an already existing object. Realize the benefits of synonyms by using them as a layer of abstraction between the underlying objects and the synonym.Suppose we have a table named 'SalesHistoryOfITDepartmentYear2008'.So instead of writting queries using this long name we can make make a synonym for this table.

CREATE SYNONYM SalesHistoryFOR SalesData.dbo.SalesHistoryOfITDepartmentYear2008;

Lets understand the use of Synonym with example.Due to expanding business and scalability needs, you decide that it's a good idea to remove the SalesHistory table from your current database named Inventory and put it in a separate database named SalesData. There is a lot of code in the Inventory database that references the SalesHistory table. Most of this code is simple queries that only read data from the SalesHistory table. The project deadline is in the very near future, so it will be difficult to change all existing code to reference the table in the new database.So we can use a synonym to drastically reduce your development time.
Assume that you have already copied your SalesHistory table into the new SalesData database and have renamed the current SalesHistory table in the Inventory database. (I always prefer renaming a table that I intend to delete first. This gives me the opportunity to discover any errors on the system caused by removing a table.)
Once you rename the SalesHistory table, you can create a synonym that references to the SalesHistory table that you have placed in the new database. The script is below.

USE InventoryGOCREATE SYNONYM SalesHistoryFOR SalesData.dbo.SalesHistory;
This synonym has created a pointer to the SalesHistory table in the new SalesData database; however, because the synonym is in the Inventory database and is named SalesHistory, any queries or DML statements executed on the SalesHistory synonym are actually executed against the SalesHistory table in the SalesData database

No comments: