SYNONYM - create aliases for your objects
MS SQL Server 2005 introduces a host of new features, some well-known; some not as familiar, but exciting like SYNONYMs.
Synonyms help us to create aliases for our objects. They replace fully qualified name into shortest user-defined name and simplify the naming of remote objects as well as objects that are stored in another database or another schema. They protect against changes in underlying objects.
Synonyms can be created for user-defined tables (including local and global temporary tables), views, assembly (CLR) stored procedure / table-valued function / scalar function / aggregate functions, replication-filter-procedure, extended stored procedure, SQL scalar function / table-valued function / inline-tabled-valued function / stored procedure. But take notice, that SYNONYMs base object will be checked only at run time.
Here is an example that directly accesses a table on another server: Normaly:
USE master EXEC sp_addlinkedserver [servername\instancename]; GO USE TEMPDB SELECT * FROM [servername\instancename]. AdventureWorks.Production.Product
And now with SYNOYM:
USE TEMPDB
CREATE SYNONYM synGetProductionProduct
FOR AdventureWorks.Production.Product;
GO
Now you can use:
SELECT * FROM synGetProductionProduct
s SQL Server versions, mostly you do this by creating a view! But you can't do that for stored procedures and functions, but now with SYNONYMs you can do something like this:
USE [AdventureWorks]
GO
CREATE FUNCTION [dbo].[ufnGetProductName]
(@ProductNumber [nvarchar] (25))
RETURNS [nvarchar](50) WITH EXECUTE AS CALLER
AS
-- Returns the name.
BEGIN
DECLARE @ProductName nvarchar (50);
SELECT @ProductName = p.[Name]
FROM [Production].[Product] p
WHERE p.[ProductNumber]= @ProductNumber
RETURN @ProductName;
END;
USE tempdb;
GO
-- Create a synonym for the
-- Product table in AdventureWorks.
CREATE SYNONYM synGetProductName
FOR AdventureWorks.dbo.ufnGetProductName;
GO
SELECT dbo.synGetProductName('AR-5381') AS ProductName
For more information about SYNONYMs search BOL
Technorati ProfileCU tosc
Print article | This entry was posted by tosc on 2008-02-27 at 14:21:07 . Follow any responses to this post through RSS 2.0. |
Tag cloud
administration backup «best practices» books bug ctp «cumulative update» demo dmv ebook humor index indexoptimize integrity kbfix links maintenance «ms sql server 2008» pass performance php reviews «ross mistry» serverproperty «service pack» «service pack 2» «service pack 3» «service packs» sharepoint «sql server» «sql server 2005» «sql server 2008 r2» «sql server 2012» «sql server 2014» sqlcat sqlpass «sqlpass franken» ssms ssmstoolspack «stacia misner» sysadmin t-sql technet «technical note» tempdb tools «trace flag» upgrade version whitepapers