Vous êtes sur la page 1sur 13

CREATE SYNONYM (Transact-SQL)

SQL Server 2014


Other Versions

Creates a new synonym.


Applies to: SQL Server (SQL Server 2008 through current version), Azure SQL Database.
Transact-SQL Syntax Conventions

Syntax
-- SQL Server Syntax
CREATE SYNONYM [ schema_name_1. ] synonym_name FOR <object>
<object> :: =
{
[ server_name.[ database_name ] . [ schema_name_2 ]. object_name
| database_name . [ schema_name_2 ].| schema_name_2. ] object_name
}
-- Windows Azure SQL Database Syntax
CREATE SYNONYM [ schema_name_1. ] synonym_name FOR < object >
< object > :: =
{
[database_name. [ schema_name_2 ].| schema_name_2. ] object_name
}

Arguments
schema_name_1
Specifies the schema in which the synonym is created. If schema is not specified, SQL
Server uses the default schema of the current user.
synonym_name
Is the name of the new synonym.

server_name
Applies to: SQL Server 2008 through SQL Server 2014.
Is the name of the server on which base object is located.
database_name
Is the name of the database in which the base object is located. If database_name is not
specified, the name of the current database is used.
schema_name_2
Is the name of the schema of the base object. If schema_name is not specified the default
schema of the current user is used.
object_name
Is the name of the base object that the synonym references.
Windows Azure SQL Database supports the three-part name format database_name.
[schema_name].object_name when the database_name is the current database or the
database_name is tempdb and the object_name starts with #.

Remarks
The base object need not exist at synonym create time. SQL Server checks for the existence of
the base object at run time.
Synonyms can be created for the following types of objects:
Assembly (CLR) Stored Procedure

Assembly (CLR) Table-valued Function

Assembly (CLR) Scalar Function

Assembly Aggregate (CLR) Aggregate Functions

Replication-filter-procedure

Extended Stored Procedure

SQL Scalar Function

SQL Table-valued Function

SQL Inline-table-valued Function

SQL Stored Procedure

View

Table1 (User-defined)

1 Includes local and global temporary tables


Four-part names for function base objects are not supported.
Synonyms can be created, dropped and referenced in dynamic SQL.

Permissions
To create a synonym in a given schema, a user must have CREATE SYNONYM permission and
either own the schema or have ALTER SCHEMA permission.
The CREATE SYNONYM permission is a grantable permission.
Note
You do not need permission on the base object to successfully compile the CREATE
SYNONYM statement, because all permission checking on the base object is deferred until run
time.

Examples
A. Creating a synonym for a local object
The following example first creates a synonym for the base object, Product in the
AdventureWorks2012 database, and then queries the synonym.
USE tempdb;
GO
-- Create a synonym for the Product table in AdventureWorks2012.
CREATE SYNONYM MyProduct
FOR AdventureWorks2012.Production.Product;
GO
-- Query the Product table by using the synonym.
USE tempdb;
GO
SELECT ProductID, Name
FROM MyProduct
WHERE ProductID < 5;

GO

Here is the result set.


----------------------ProductID Name
----------- -------------------------1 Adjustable Race
2 Bearing Ball
3 BB Ball Bearing
4 Headset Ball Bearings
(4 row(s) affected)

B. Creating a synonym to remote object


In the following example, the base object, Contact, resides on a remote server named
Server_Remote.
Applies to: SQL Server 2008 through SQL Server 2014.
EXEC sp_addlinkedserver Server_Remote;
GO
USE tempdb;
GO
CREATE SYNONYM MyEmployee FOR
Server_Remote.AdventureWorks2012.HumanResources.Employee;
GO

C. Creating a synonym for a user-defined function


The following example creates a function named dbo.OrderDozen that increases order amounts
to an even dozen units. The example then creates the synonym dbo.CorrectOrder for the
dbo.OrderDozen function.
-- Creating the dbo.OrderDozen function
CREATE FUNCTION dbo.OrderDozen (@OrderAmt int)
RETURNS int
WITH EXECUTE AS CALLER
AS
BEGIN
IF @OrderAmt % 12 <> 0

BEGIN
SET @OrderAmt +=
END
RETURN(@OrderAmt);
END;
GO

12 - (@OrderAmt % 12)

-- Using the dbo.OrderDozen function


DECLARE @Amt int;
SET @Amt = 15;
SELECT @Amt AS OriginalOrder, dbo.OrderDozen(@Amt) AS ModifiedOrder;
-- Create a synonym dbo.CorrectOrder for the dbo.OrderDozen function.
CREATE SYNONYM dbo.CorrectOrder
FOR dbo.OrderDozen;
GO
-- Using the dbo.CorrectOrder synonym.
DECLARE @Amt int;
SET @Amt = 15;
SELECT @Amt AS OriginalOrder, dbo.CorrectOrder(@Amt) AS ModifiedOrder;

CREATE SYNONYM
Purpose
To create a synonym. A synonym is an alternative name for a table, view, sequence, procedure,
stored function, package, snapshot, or another synonym.

Prerequisites
To create a private synonym in your own schema, you must have CREATE SYNONYM system
privilege.
To create a private synonym in another user's schema, you must have CREATE ANY
SYNONYM system privilege. If you are using Trusted Oracle7 in DBMS MAC mode, your
DBMS label must dominate the creation label of the owner of schema to contain the synonym.
To create a PUBLIC synonym, you must have CREATE PUBLIC SYNONYM system privilege.

Syntax

Keywords and Parameters


PUBLIC
creates a public synonym. Public synonyms are accessible to all users. If you omit this option,
the synonym is private and is accessible only within its schema.
schema
is the schema to contain the synonym. If you omit schema, Oracle7 creates the synonym in your
own schema. You cannot specify schema if you have specified PUBLIC.
synonym
is the name of the synonym to be created.
FOR
identifies the object for which the synonym is created. If you do not qualify object with schema,
Oracle7 assumes that the object is in your own schema. The object can be of the following types:

table

view

sequence

stored procedure, function, or package

snapshot

synonym

The object cannot be contained in a package.


Note that the object need not currently exist and you need not have privileges to access the
object.
You can use a complete or partial dblink to create a synonym for an object on a remote database
where the object is located. For more information on referring to database links, see the section,
"Referring to Objects in Remote Databases," . If you specify dblink and omit schema, the
synonym refers to an object in the schema specified by the database link. It is recommended that
you specify the schema containing the object in the remote database.
If you omit dblink, Oracle7 assumes the object is located on the local database.

Usage Notes
In Trusted Oracle7, the new synonym is automatically labeled with your DBMS label.
A synonym can be used to stand for its base object in any of the following Data Manipulation
Language statements:

SELECT

INSERT

UPDATE

DELETE

EXPLAIN PLAN

LOCK TABLE

Synonyms can also be used in the following Data Definition Language statements:

AUDIT

NOAUDIT

GRANT

REVOKE

COMMENT

Synonyms are used for security and convenience. Creating a synonym for an object allows you
to:

reference the object without specifying its owner

reference the object without specifying the database on which it is located

provide another name for the object

Synonyms provide both data independence and location transparency; synonyms permit
applications to function without modification regardless of which user owns the table or view
and regardless of which database holds the table or view.

Scope of Synonyms
A private synonym name must be distinct from all other objects in its schema. Oracle7 attempts
to resolve references to objects at the schema level before resolving them at the PUBLIC
synonym level. Oracle7 only uses a public synonym when resolving references to an object if
both of the following cases are true:

the object is not prefaced by a schema

the object is not followed by a database link

For example, assume the schemas SCOTT and BLAKE each contain tables named DEPT and the
user SYSTEM creates a PUBLIC synonym named DEPT for BLAKE.DEPT. If the user SCOTT
then issues the following statement, Oracle7 returns rows from SCOTT.DEPT:
SELECT *
FROM dept

To retrieve rows from BLAKE.DEPT, the user SCOTT must preface DEPT with the schema
name:

SELECT *
FROM blake.dept

If the user ADAM's schema does not contain an object named DEPT, then ADAM can access the
DEPT table in BLAKE's schema by using the public synonym DEPT:
SELECT *
FROM dept

Example I
To define the synonym MARKET for the table MARKET_RESEARCH in the schema SCOTT,
issue the following statement:
CREATE SYNONYM market
FOR scott.market_research

Example II
To create a PUBLIC synonym for the EMP table in the schema SCOTT on the remote SALES
database, you could issue the following statement:
CREATE PUBLIC SYNONYM emp
FOR scott.emp@sales

Note that a synonym may have the same name as the base table provided the base table is
contained in another schema.

Related Topics
CREATE DATABASE LINK command CREATE TABLE command CREATE VIEW
command

Aliases and Synonyms


Different databases are organized in quite different ways. Even the word database itself has
completely different meanings in different RDBMS implementations. For example, an Oracle
database is a totally self-contained and independent entity with its own set of users, tables,
indexes, and other objects invisible to other databases. Each Oracle database user can have
his/her own tables, views, indexes, and so on. (In Oracle terms USER and SCHEMA are often
used as synonyms which adds confusion.) To access objects that belong to another user (or are
within another schema), you have to be granted appropriate permissions (see Chapter 12) and
you also have to use fully qualified names (schema_name.object_name). For example, if USER1
wants to select records from SHIPMENT table that belongs to USER3, the query would look like
this:
SELECT * FROM

USER3.SHIPMENT;

Assuming SHIPMENT always means USER3.SHIPMENT for USER1, typing fully qualified
name makes queries longer and less readable.
Note
The synonyms are especially important when users who don't own objects need to access
the database using an application with embedded SQL (discussed in Chapter 15). The
programming effort to make such applications work properly without synonyms would
increase tremendously.
Figure 4-6 illustrates Oracle's database organization.

Figure 4-6: Database organization in


Oracle
The Oracle RDBMS lets you to create synonyms to deal with the problem. A synonym is a name
that translates into another name whenever it is referenced. In other words, we can say that a
synonym is an alternative name for a database object. You can create the synonym SHIPMENT
for USER3.SHIPMENT and use it any time you need to access the USER3.SHIPMENT table.
DB2 UDB organization is quite similar; a database object that is simply a different name for
another database object is called ALIAS.
The structure of MS SQL Server is different. There can be many databases within a single SQL
Server. Users (or logins) are created on the server level and can have access to many databases
while the database objects belong to a single owner (usually called dbo). See Figure 4-7.

Figure 4-7: Database organization in MS SQL Server

SQL99
Synonyms and aliases are not a part of SQL99 standards.

Oracle 9i CREATE SYNONYM statement


The syntax for the CREATE SYNONYM statement is
CREATE [PUBLIC] SYNONYM
[<schema>.]<synonym_name> FOR
[<schema>.]<object_name>[@<dblink>];

Public versus private synonyms


In Oracle, you can create public synonyms accessible to all database users or private ones visible
only to their owners. Use keyword PUBLIC if you want to create a public synonym or skip it
otherwise. (Keyword PRIVATE is invalid.)
Types of objects you can create synonyms for
You can create synonyms for the following Oracle objects: table, view, sequence, stored
procedure, function, package, materialized view, and Java class schema object. You can also
create a synonym for another synonym.
Creating synonyms for remote database objects

You can create synonyms for objects located in remote databases assuming a database link exists
for those databases. More about database links later in this chapter.
CREATE SYNONYM examples
The following example creates the public synonym SHIPMENT for a hypothetical table
USER3.SHIPMENT:
CREATE PUBLIC SYNONYM

shipment FOR user3.shipment;

The next statement illustrates the creation of private synonym EMP for a USERn.EMPLOYEE
table in USER2 schema:
CREATE SYNONYM user2.emp FOR
usern.employee;

Note that you could skip USER2 if the above statement was issued by USER2 him/herself; it is
mandatory though if the synonym EMP is being created by, say, the database administrator for
USER2.
Note
Even though synonyms can be very useful, they also can cause lots of confusion. The most
typical situation is when a user has objects in his/her schema with exactly the same names
as public or private synonyms. Oracle tries to resolve names looking in the users' schema
first, and if the name is found, RDBMS assumes that's the one to use. So, if there are views
USER1.VIEW1 and USER2.VIEW1 in the database, and there is also public synonym
VIEW1 for USER2.VIEW1 that is supposed to be used in all user queries, USER1 might
have serious program errors (if the columns of his/her VIEW1 are different from
USER2.VIEW1). Or, which is sometimes even worse because it's more difficult to notice,
incorrect results (if the column definitions are identical, but the views use different
underlying tables or join them in a different way).
Tip
In Oracle you can create synonyms for nonexistent objects; if the objects are created later
they can be referred using those synonyms. You can also create synonyms for objects you
don't have privileges to access, but doing so will not give you an access to those objects.

DB2 UDB 8.1 CREATE ALIAS/SYNONYM statement


You can use either the CREATE SYNONYM or the CREATE ALIAS statement. Aliases can be
created for tables, views, or other aliases. The syntax is
CREATE {ALIAS | SYNONYM}
<alias_name> FOR <object_name>

In DB2, you cannot create an alias with a name identical to one of a table, view, or another alias
that already exists in the current database. That resolves the problem described in the previous
section about Oracle's synonyms, but makes using aliases in DB2 less flexible.
Here are examples that create aliases in DB2:
CREATE ALIAS shipmt FOR
user3.shipment
CREATE ALIAS emp FOR
usern.employee

Note that the following statement returns an error (assuming you are using objects shown in
Figure 4-6) because the table named SHIPMENT exists in schema USER3:
CREATE PUBLIC SYNONYM SHIPMENT
FOR USER3.SHIPMENT;

Like Oracle, DB2 allows you to create synonyms for objects that do not yet exist, though a
warning will be issued.

MS SQL Server 2000


MS SQL Server does not let you create aliases or synonyms. This limitation is justified by its
database structure (Figure 4-7).
- See more at:
http://etutorials.org/SQL/SQL+Bible+Oracle/Part+II+Creating+and+Modifying+Database+Obje
cts/Chapter+4+Creating+RDBMS+Objects/Aliases+and+Synonyms/#sthash.1MOsxJ88.dpuf

Vous aimerez peut-être aussi