Synonyms in SQL Server 2005

http://nayyeri.net/archive/2007/08/27/synonyms-in-sql-server-2005.aspx

Naming conventions are always a big concern for developers whether they're an application developer or database developers!  Naming tables, columns, views, stored procedures and other objects in a database sometimes gets harder than what we think, especially when we're working on multiple objects with same name from two different databases, tables or ...

SQL Server 2005 introduced a new feature for synonyms that come handy to assign alternative names for a database object in order to work with it easier.  CREATE SYNONYM is a new statement that lets you assign these alternative names.

You can define a synonym on a two-part, three-part or four-part object name.  The scope of synonyms is limited to the database where they're defined in!  Synonyms can be defined for some objects like:

  • Table
  • View
  • Stored Procedure
  • Function
  • Replication filter procedure
  • Extended stored procedure

Let me give an example.  Suppose that I have a database named MyDB with a table named MyTable.  This table contains three columns: ID, Name and Age.  I create some sample data in this table.

Now I can assign an alternative name to MyTable like AltMyTable as you see.

CREATE SYNONYM dbo.AltMyTable FOR MyTable
SELECT * FROM AltMyTable

This simply returns data from MyTable.

As another example, I also create a simple stored procedure to select data from MyTable and name it SelectData.

IF EXISTS (SELECT * FROM sysobjects WHERE type = 'P' AND name = 'SelectData')
BEGIN
DROP Procedure Stored_Procedure_Name
END
GO
CREATE Procedure SelectData
AS
SELECT * FROM MyTable
GO

Now I assign a new name like SelectMyData to this stored procedure.

CREATE SYNONYM dbo.SelectMyData FOR SelectData
EXECUTE SelectMyData

You can also check your synonyms from the explorer easily.

你可能感兴趣的:(sql,server,2005)