Удалить синоним oracle

В этом учебном материале вы узнаете, как создавать и удалять синонимы (create and drop synonyms) в Oracle/PLSQL с синтаксисом и примерами.

Описание

В Oracle/PLSQL Synonym это альтернативное имя для таких объектов, как таблицы, представления, последовательности, хранимые процедуры и другие объекты базы данных.
Как правило, вы используете синонимы, когда предоставляете доступ к объекту из другой схемы, и вы не хотите, чтобы пользователи беспокоились о том, к какой схеме относится объект.

Create (or Replace) Synonym

Вы можете создать синоним, так чтобы пользователи не использовали префикс имени таблицы с именем схемы, при использовании таблицы в запросе.

Синтаксис

Синтаксис для создания синонимов Oracle/PLSQL:

CREATE [OR REPLACE] [PUBLIC] SYNONYM [schema .] synonym_name
FOR [schema .] object_name [@ dblink];

OR REPLACE
Позволяет пересоздать синоним (если он уже существует), без необходимости выдавать команду DROP synonym.
PUBLIC
Это означает, что синоним является публичным и доступен для всех пользователей. Помните, что пользователь сначала должен иметь соответствующие привилегии для объекта использования синонима.
schema
Соответствующая схема. Если эта фраза опущена, Oracle предполагает, что вы имеете в виду вашу собственную схему.
object_name
Имя объекта, для которого вы создаете синоним. Это может быть один из следующих объектов:

  • table
  • view
  • sequence
  • stored procedure
  • function
  • package
  • materialized view
  • java class schema object
  • user-defined object
  • synonym

Пример

Рассмотрим пример того, как создать синоним в Oracle/PLSQL.

Например:

CREATE PUBLIC SYNONYM suppliers

FOR app.suppliers;

Этот первый пример CREATE SYNONYM демонстрирует, как создать синоним с названием suppliers. Теперь, пользователи других схем могут ссылаться на таблицу с suppliers без префикса с именем схемы и именем таблицы.

Например:

Если это синоним уже существует, и вы хотите его пересоздать, то можете использовать OR REPLACE следующим образом:

CREATE OR REPLACE PUBLIC SYNONYM suppliers

FOR app.suppliers;

Drop synonym

После того, как синоним был создан в Oracle, вам в какой-то момент понадобится его удалить.

Синтаксис

Синтаксис drop synonym в Oracle/PLSQL:

DROP [PUBLIC] SYNONYM [schema .] synonym_name [force];

PUBLIC
Позволяет удалить public synonym. Если вы указали PUBLIC, то можете не указывать схему.
force
Это принудит Oracle удалить synonym, даже если он имеет зависимости. Это, вероятно, не очень хорошая идея, чтобы использовать force, поскольку это может привести к недействительности объектов Oracle.

Пример

Рассмотрим пример того, как удалить synonym в Oracle/PLSQL.

Например:

DROP PUBLIC SYNONYM suppliers;

Оператор DROP удалит синоним с названием suppliers, который мы определяли ранее.

Summary: in this tutorial, you will learn how to use the Oracle DROP SYNONYM statement to remove a synonym from the database.

Introduction to Oracle DROP SYNONYM statement

The DROP SYNONYM statement allows you to delete a synonym from the database. Here is the basic syntax of the DROP SYNONYM statement:

DROP SYNONYM schema.synonym_name FORCE;

Code language: SQL (Structured Query Language) (sql)

In this syntax:

  • First, specify the name of the synonym that you want to remove after the DROP SYNONYM keyword. If the synonym belongs to a schema, you must specify its schema name. If you skip the schema name, Oracle will assume that you delete the synonym in your own schema.
  • Second, use the FORCE keyword to delete the synonym even if it has dependent tables or user-defined types.

To drop a public synonym, you use the PUBLIC keyword as follows:

DROP PUBLIC SYNONYM synonym_name FORCE;

Code language: SQL (Structured Query Language) (sql)

Note that you cannot specify the schema name when you use the PUBLIC keyword.

If you want to drop a private synonym, you must be the owner of the schema to which the synonym belongs or you must have the DROP ANY SYNONYM privilege. In case you want to drop a PUBLIC synonym, you must have the DROP PUBLIC SYNONYM privilege.

Oracle DROP SYNONYM example

The following example uses the DROP SYNONYM statement to delete the stocks synonym created in the CREATE SYNONYM tutorial:

DROP SYNONYM stocks;

Code language: SQL (Structured Query Language) (sql)

Oracle issued the following message:

Synonym STOCKS dropped.

Code language: SQL (Structured Query Language) (sql)

In this tutorial, you have learned how to use the Oracle DROP SYNONYM statement to delete a synonym from the database.

Was this tutorial helpful?

totn Oracle / PLSQL


Oracle / PLSQL: Synonyms

This Oracle tutorial explains how to create and drop synonyms in Oracle with syntax and examples.

Description

A synonym is an alternative name for objects such as tables, views, sequences, stored procedures, and other database objects.

You generally use synonyms when you are granting access to an object from another schema and you don’t want the users to have to worry about knowing which schema owns the object.

Create Synonym (or Replace)

You may wish to create a synonym so that users do not have to prefix the table name with the schema name when using the table in a query.

Syntax

The syntax to create a synonym in Oracle is:

CREATE [OR REPLACE] [PUBLIC] SYNONYM [schema .] synonym_name
  FOR [schema .] object_name [@ dblink];
OR REPLACE
Allows you to recreate the synonym (if it already exists) without having to issue a DROP synonym command.
PUBLIC
It means that the synonym is a public synonym and is accessible to all users. Remember though that the user must first have the appropriate privileges to the object to use the synonym.
schema
The appropriate schema. If this phrase is omitted, Oracle assumes that you are referring to your own schema.
object_name
The name of the object for which you are creating the synonym. It can be one of the following:

  • table
  • view
  • sequence
  • stored procedure
  • function
  • package
  • materialized view
  • java class schema object
  • user-defined object
  • synonym

Example

Let’s look at an example of how to create a synonym in Oracle.

For example:

CREATE PUBLIC SYNONYM suppliers
FOR app.suppliers;

This first CREATE SYNONYM example demonstrates how to create a synonym called suppliers. Now, users of other schemas can reference the table called suppliers without having to prefix the table name with the schema named app. For example:

SELECT *
FROM suppliers;

If this synonym already existed and you wanted to redefine it, you could always use the OR REPLACE phrase as follows:

CREATE OR REPLACE PUBLIC SYNONYM suppliers
FOR app.suppliers;

Drop synonym

Once a synonym has been created in Oracle, you might at some point need to drop the synonym.

Syntax

The syntax to drop a synonym in Oracle is:

DROP [PUBLIC] SYNONYM [schema .] synonym_name [force];
PUBLIC
Allows you to drop a public synonym. If you have specified PUBLIC, then you don’t specify a schema.
force
It will force Oracle to drop the synonym even if it has dependencies. It is probably not a good idea to use force as it can cause invalidation of Oracle objects.

Example

Let’s look at an example of how to drop a synonym in Oracle.

For example:

DROP PUBLIC SYNONYM suppliers;

This DROP statement would drop the synonym called suppliers that we defined earlier.

Dear readers of our blog, we’d like to recommend you to visit the main page of our website, where you can learn about our product SQLS*Plus and its advantages.

SQLS*Plus — best SQL Server command line reporting and automation tool! SQLS*Plus is several orders of magnitude better than SQL Server sqlcmd and osql command line tools.

Enteros UpBeat offers a patented database performance management SaaS platform. It proactively identifies root causes of complex revenue-impacting database performance issues across a growing number of RDBMS, NoSQL, and deep/machine learning database platforms. We support Oracle, SQL Server, IBM DB2, MongoDB, Casandra, MySQL, Amazon Aurora, and other database systems.

17 August 2020

Oracle Synonym

In Oracle PLSQL Synonym is an alternative name for objects such as tables, views, sequences, stored procedures and other database objects.

Typically, you use synonyms when you provide access to an object from another schema, and you don’t want users to worry about which schema the object belongs to.

Create (or Replace) Synonym

You can create a synonym so that users do not use a table name prefix with the schema name when using a table in a query.

Syntax for creating Oracle/PLSQL synonyms

CREATE [OR REPLACE] [PUBLIC] SYNONYM [schema .] synonym_name
FOR [schema .] object_name [@ dblink];
OR REPLACE

Allows you to recreate a synonym (if it already exists), without having to issue the DROP synonym command.

  • PUBLIC – This means that the synonym is public and available to all users. Remember that the user must first have the appropriate privileges for the synonym object.
  • schema – The appropriate schema. If this phrase is omitted, Oracle assumes that you are referring to your own schema.
  • object_name – The name of the object for which you are creating the synonym. It can be one of the following objects:
  1. table
  2. view
  3. sequence
  4. stored procedure
  5. function
  6. package
  7. materialized view
  8. java class schema object
  9. user-defined object
  10. synonym

Let’s consider an example of how to create a synonym in Oracle/PLSQL

CREATE PUBLIC SYNONYM suppliers
FOR app;

This first example of CREATE SYNONYM demonstrates how to create a synonym with the name. Now, users of other schemes can reference the table with suppliers without the prefix of the scheme name and table name.

SELECT *
FROM suppliers;

If this synonym already exists and you want to recreate it, you can use OR REPLACE as follows:

CREATE OR REPLACE PUBLIC SYNONYM suppliers
FOR app.suppliers;

Drop synonym

After the synonym was created in Oracle, you will need to remove it at some point.

drop synonym syntax in Oracle/PLSQL

DROP [PUBLIC] SYNONYM [schema .] synonym_name [force];

  • PUBLIC – Allows you to remove the public synonym. If you specified a PUBLIC, you may not need to specify a schema.
  • Force – This will force Oracle to remove the synonym, even if it has dependencies. This is probably not a good idea to use force, as it can invalidate Oracle objects.

Let us consider an example of how to remove synonym in Oracle/PLSQL

For example:

DROP PUBLIC SYNONYM;

The DROP operator will delete the synonym with the name of suppliers that we defined earlier.

Oracle – SQL – Creating Synonyms



Tags: Oracle, Oracle Database, Oracle SQL, PL/SQL, PLSQL, SQL

Oracle Synonyms

Introduction to Oracle Synonyms

Oracle Synonym can be defined as the word itself literary means that it is actually are aliases for referencing data objects which include tables, sequences, stored functions, and stored procedures along with many other objects which can be stored in the database basically granting permission to access the data object of this schema by the user of another schema without the user having any worry of the permissions required to access the data object.

How to create Synonyms in Oracle?

As we have discussed in the earlier section of the article about what is an Oracle SYNOBYM. Let us now discuss how we can create a synonym. At first, let us look at the syntax for the creation of a SYNONYM.

Syntax

CREATE [OR REPLACE] [PUBLIC] SYNONYM schema.synonym_name
FOR schema.object_name;

Parameters

  • REPLACE: This parameter is used to recreate the same synonym if it already exists; the user is not required to drop the existing synonym.
  • PUBLIC: This parameter as the name suggests is used to create a synonym that is public. The term public means that the synonym is applicable or accessible to all users. One important point to remember is that the privileges should already be present with the user for the objects to make it public.
  • schema: This parameter is used to give the schema name. If we omit this parameter then the oracle will think it to be the user’s own schema.
  • object_name: This parameter refers to the name of the object for which we are creating the schema. These objects can be table, view, sequence, function, and stored procedure.

Let us now go through an example to understand better. In our example we will create a synonym for the table employee which is present in the schema ‘nil’ and after creating the schema we will try to access it from a different schema. Let us first write a query to create a schema for the table employee.

Code #1

CREATE PUBLIC SYNONYM employee_nil
FOR nil.employee;

In the above query, the synonym name is employee_nil. After we have created the synonym, now we can use the name employee_nil instead of an employee to access it as it is also created as public. Let us write a query as now we o not have to prefix the schema name with the table name. Let us now execute the query in SQL developer and look at the result.

Output:

Oracle Synonyms - 1

As per the screenshot, we can see that the synonym employee_nil has been created.

Code #2

SELECT * FROM employee_nil;

As per our discussion in the above section, this query when executed in the SQL developer should return us the result set of the employee table. Let us execute and check the result.

Output:

Oracle Synonyms - 2

As we can see in the above screenshot that the query returns the rows of the employee table.

How to Drop Synonyms in Oracle?

In the previous section of the article, we created the synonym using the CREATE SYNONYM statement. Now as we are aware that if we can create a synonym of an object then in the due course we may need to drop the same synonym. In this section of the article we will discuss how we can drop an already created synonym. Let us first check the SYNTAX for dropping the synonym.

Syntax

DROP [PUBLIC] SYNONYM schema . synonym_name [force];

Parameters

  • PUBLIC: As the name suggests, it allows the user to drop any PUBLIC synonym. One more important point is that we do not need to use the schema name as a prefix as we have already used PUBLIC.
  • synonym_name: As the name suggests it refers to the name of the synonym.
  • Force: If we use this parameter at the end of the query then the oracle database will drop the synonym forcibly even it has dependencies. We should not use this often as it may cause later validation issues.

Let us now go through an example to understand this concept better. Now, in the previous section of this article, we had created a PUBLIC SYNONYM called employee_nil. We are going to delete the same PUBLIC SYNONYM in this section using the DROP SYNONYM statement. Let us have a look at the query.

Code:

DROP PUBLIC SYNONYM employee_nil;

As we can see that we have not used the schema name in the query because since it is already created as a public schema so it is not required. We have also not used the force parameter in the query since it does not have any dependencies on any other data objects. It is also advised not to use the force parameters often. Let us now execute the query in SQL developer and check the result.

Output:

Oracle Synonyms - 3

As we can see in the above screenshot the Public synonym EMPLOYEE_NIL has been dropped.

Advantages of Using Oracle Synonym

In the above two sections, we discussed how to create and drop the Oracle synonyms. Now, in this section, we will look into the advantages of using Oracle Synonym.

So, let us look at the few advantages below.

  • In the earlier part of the article, we discussed that the synonym can be called as an alias so synonyms actually help us to shorten the names of the lengthy table names especially from different schemas as in that we need to write the whole schema name which itself can be lengthy and complicated.
  • It helps in backward compatibility which means that if there is a table in a legacy application and we rename that table but do not the current applications using it to get hampered. In that case, we can create a synonym that has the same name as the old table name.

Conclusion

In this article we have discussed the definition of Oracle Synonyms and then later we discussed in detail along with examples about how to create a synonym and then also drop the synonym. We also discussed the various advantages that we can get with the oracle synonym.

Recommended Articles

This is a guide to Oracle Synonyms. Here we discuss an introduction to Oracle Synonyms, how to create drop synonyms with examples for understanding better. You can also go through our other related articles to learn more –

  1. Oracle COMMIT 
  2. Oracle Self Join
  3. Oracle WILDCARDS
  4. Function in Oracle

Понравилась статья? Поделить с друзьями:
  • Удалить зуб синоним
  • Удались на славу синоним
  • Удар ногой синоним
  • Удаленный сотрудник синоним
  • Удар ниже пояса синоним