Статьи

Синоніми (ядро СУБД) - SQL Server

  1. Синоніми та схеми Synonyms and Schemas
  2. Надання дозволів на синонім Granting Permissions on a Synonym
  3. Використання синонімів Using Synonyms
  4. приклади Examples
  5. Див. Також Related Content

ОБЛАСТЬ ЗАСТОСУВАННЯ: ОБЛАСТЬ ЗАСТОСУВАННЯ:   SQL Server   База даних SQL Azure   Сховище даних SQL Azure   Parallel Data Warehouse APPLIES TO:   SQL Server   Azure SQL Database   Azure SQL Data Warehouse   Parallel Data Warehouse   Синонімом є об'єкт бази даних, який виконує наступні функції: A synonym is a database object that serves the following purposes:   надає альтернативне ім'я для іншого об'єкта бази даних, існуючого на локальному або віддаленому сервері, на яке потім посилаються як на базовий об'єкт;  Provides an alternative name for another database object, referred to as the base object, that can exist on a local or remote server SQL Server База даних SQL Azure Сховище даних SQL Azure Parallel Data Warehouse APPLIES TO: SQL Server Azure SQL Database Azure SQL Data Warehouse Parallel Data Warehouse

Синонімом є об'єкт бази даних, який виконує наступні функції: A synonym is a database object that serves the following purposes:

  • надає альтернативне ім'я для іншого об'єкта бази даних, існуючого на локальному або віддаленому сервері, на яке потім посилаються як на базовий об'єкт; Provides an alternative name for another database object, referred to as the base object, that can exist on a local or remote server.

  • забезпечує рівень абстракції, що захищає клієнтські програми від змін, вироблених в імені або місцезнаходження базових об'єктів. Provides a layer of abstraction that protects a client application from changes made to the name or location of the base object.

Наприклад, розглянемо таблицю Employee зразка бази даних Adventure Works Adventure Works, розташовану на сервері Server1. For example, consider the Employee table of Adventure Works Adventure Works , located on a server named Server1. Для доступу до цієї таблиці сервера Server2 клієнтське додаток повинен вказати ім'я з чотирьох компонентів: Server1.AdventureWorks.Person.Employee. To reference this table from another server, Server2, a client application would have to use the four -part name Server1.AdventureWorks.Person.Employee. Якби таблицю потрібно було перемістити, наприклад, на інший сервер, клієнтське додаток також треба було б модифікувати, щоб відобразити її нове місце розташування. Also, if the location of the table were to change, for example, to another server, the client application would have to be modified to reflect that change.

Для вирішення обох цих проблем на сервері Server2 можна створити синонім - EmpTable -для таблиці Employee, розташованої на Server1. To address both these issues, you can create a synonym, EmpTable, on Server2 for the Employee table on Server1. Тепер клієнтського додатку необхідно вказувати ім'я таблиці, що складається всього з одного елемента EmpTable, для звернення до таблиці Employee. Now, the client application only has to use the single -part name, EmpTable, to reference the Employee table. Крім того, якщо місце розташування таблиці Employee буде змінено, потрібно буде тільки змінити синонім EmpTable, щоб він вказував на нове місце розташування таблиці Employee. Also, if the location of the Employee table changes, you will have to modify the synonym, EmpTable, to point to the new location of the Employee table . Так як інструкції ALTER SYNONYM не існує, для цього спочатку видаляють синонім EmpTable, а потім повторно створюють його з тим же ім'ям, вказуючи нове місце розташування таблиці Employee. Because there is no ALTER SYNONYM statement, you first have to drop the synonym, EmpTable, and then re-create the synonym with the same name, but point the synonym to the new location of Employee .

Синонім належить схемою, і, як і для всіх інших об'єктів схеми, ім'я синоніма має бути унікальним в її межах. A synonym belongs to a schema, and like other objects in a schema, the name of a synonym must be unique. Синоніми можуть бути створені для наступних об'єктів бази даних. You can create synonyms for the following database objects:

Процедура складання (середа CLR) Assembly (CLR) stored procedure повертається табличне значення функція збірки (середа CLR) Assembly (CLR) table-valued function Скалярная функція збірки (середа CLR) Assembly (CLR) scalar function Агрегатна функція збірки (середа CLR) Assembly (CLR) aggregate functions процедура фільтра реплікації Replication-filter-procedure Розширена збережена процедура Extended stored procedure Скалярная функція SQL SQL scalar function повертає табличне значення функція SQL SQL table-valued function повертає табличне значення вбудована функція SQL SQL inline-tabled-valued function збережена процедура SQL SQL stored procedure Подання View Т Абліцов * (для користувача) Table * (User-defined)

* Включає локальні і глобальні тимчасові таблиці * Includes local and global temporary tables

Примітка

Імена, що складаються з чотирьох елементів, для базових об'єктів-функцій не підтримуються. Four-part names for function base objects are not supported.

Синонім не може бути базовим об'єктом для іншого синоніма, а також не може посилатися на обумовлену користувачем агрегатную функцію. A synonym can not be the base object for another synonym, and a synonym can not reference a user-defined aggregate function.

Синонім пов'язаний з його базовим об'єктом тільки по імені. The binding between a synonym and its base object is by name only. Будь-які перевірки на існування, тип і дозволу для базового об'єкта відкладаються до стадії виконання. All existence, type, and permissions checking on the base object is deferred until run time. Таким чином, базовий об'єкт може бути змінений, видалений або замінений іншим об'єктом, що має те ж ім'я, що і вихідний. Therefore, the base object can be modified, dropped, or dropped and replaced by another object that has the same name as the original base object. Наприклад, припустимо, що синонім MyContacts посилається на таблицю Person.Contact в базі даних Adventure Works Adventure Works. For example, consider a synonym, MyContacts, that references the Person.Contact table in Adventure Works Adventure Works . Якщо таблиця Contact видаляється і замінюється уявленням з ім'ям Person.Contact, синонім MyContacts буде вказувати на уявлення Person.Contact. If the Contact table is dropped and replaced by a view named Person.Contact , MyContacts now references the Person.Contact view.

Посилання на синоніми не прив'язані до схеми. References to synonyms are not schema-bound. Таким чином, синонім може бути видалений в будь-який момент. Therefore, a synonym can be dropped at any time. Проте видалення синоніма може виявитися загрожує тим, що залишаться незв'язані посилання на нього, However, by dropping a synonym, you run the risk of leaving dangling references to the synonym that was dropped. що проявиться лише на стадії виконання. These references will only be found at run time.

Синоніми та схеми Synonyms and Schemas

Якщо користувач створює синонім в схемі, власником якої він не є, ім'я синоніма необхідно випереджати ім'ям схеми, власником якої є користувач. If you have a default schema that you do not own and want to create a synonym, you must qualify the synonym name with the name of a schema that you do own. Наприклад, якщо користувач володіє схемою x, але У поточному плані є y, то при виконанні інструкції CREATE SYNONYM ім'я синоніма необхідно випереджати схемою x, а не вказувати його по імені, що складається з одного елемента. For example, if you own a schema x, but y is your default schema and you use the CREATE SYNONYM statement , you must prefix the name of the synonym with the schema x , instead of naming the synonym by using a single -part name. Додаткові відомості про те, як створювати синоніми, див. Розділ CREATE SYNONYM (Transact-SQL) . For more information about how to create synonyms, see CREATE SYNONYM (Transact-SQL) .

Надання дозволів на синонім Granting Permissions on a Synonym

Тільки власники синоніма або члени ролей db_owner і db_ddladmin можуть надавати дозволи на синонім. Only synonym owners, members of db_owner, or members of db_ddladmin can grant permission on a synonym .

Для синоніма вибрати GRANT, DENY і REVOKE для всіх або будь-яких дозволів з нижчеперелічених: You can GRANT, DENY, and REVOKE all or any of the following permissions on a synonym:

CONTROL CONTROL DELETE DELETE EXECUTE EXECUTE INSERT INSERT SELECT SELECT TAKE OWNERSHIP TAKE OWNERSHIP UPDATE UPDATE VIEW DEFINITION VIEW DEFINITION

Використання синонімів Using Synonyms

Можна використовувати синоніми замість їх базового об'єкта, на який вони посилаються, в декількох інструкціях SQL і контекстах вираження. You can use synonyms in place of their referenced base object in several SQL statements and expression contexts. Наступна таблиця містить список цих інструкцій і контекстів вираження. The following table contains a list of these statements and expression contexts:

SELECT SELECT INSERT INSERT UPDATE UPDATE DELETE DELETE EXECUTE EXECUTE Підзапити вибірки Sub-selects

При роботі з синонімами в сформульованих раніше контекстах буде порушено базовий об'єкт. When you are working with synonyms in the contexts previously stated, the base object is affected. Наприклад, якщо синонім посилається на базовий об'єкт, який є таблицею, і рядок вставляється в синонім, то фактично рядок вставляється в таблицю, на яку посилається синонім. For example, if a synonym references a base object that is a table and you insert a row into the synonym, you are actually inserting a row into the referenced table.

Примітка

Не можна послатися на синонім, який розташований на пов'язаному сервері. You can not reference a synonym that is located on a linked server.

Синонім можна використовувати в якості параметра функції OBJECT_ID; однак ця функція поверне ідентифікатор об'єкта для синоніма, а не для базового об'єкта. You can use a synonym as the parameter for the OBJECT_ID function; however, the function returns the object ID of the synonym, not the base object.

Не можна посилатися на синонім в інструкції DDL. You can not reference a synonym in a DDL statement. Наприклад, такі інструкції, що посилаються на синонім dbo.MyProduct, приведуть до помилки. For example, the following statements, which reference a synonym named dbo.MyProduct, generate errors:

ALTER TABLE dbo.MyProduct ADD NewFlag int null; EXEC ( 'ALTER TABLE dbo.MyProduct ADD NewFlag int null');

Наступні інструкції дозволів пов'язані тільки з синонімом, а не з базовим об'єктом. The following permission statements are associated only with the synonym and not the base object:

GRANT GRANT DENY DENY REVOKE REVOKE

Синоніми не прив'язані до схеми, і тому на них не можна посилатися наступними прив'язаними до схеми контекстами вираження. Synonyms are not schema-bound and, therefore, can not be referenced by the following schema-bound expression contexts:

CHECK, обмеження CHECK constraints Обчислювані стовпці Computed columns Вирази за замовчуванням Default expressions Вирази правил Rule expressions прив'язані до схеми подання Schema-bound views прив'язані до схеми функції Schema-bound functions

Додаткові відомості про прив'язаних до схеми функціях див. Розділ Створення визначених користувачем функцій (компонент Database Engine) . For more information about schema-bound functions, see Create User-defined Functions (Database Engine) .

Представлення каталогу sys.synonyms містить запис для кожного синоніма в даній базі даних. The sys.synonyms catalog view contains an entry for each synonym in a given database. Це уявлення каталогу забезпечує доступ до таких метаданих, як ім'я синоніма і ім'я базового об'єкта. This catalog view exposes synonym metadata such as the name of the synonym and the name of the base object. Додаткові відомості див. У розділі sys.synonyms (Transact-SQL) . For more information, see sys.synonyms (Transact-SQL) .

За допомогою розширених властивостей можна додавати описовий або керуючий текст, маски введення і правила форматування у вигляді властивостей синоніма. By using extended properties, you can add descriptive or instructional text, input masks, and formatting rules as properties of a synonym. Так як властивості зберігаються в базі даних, всі програми, що зчитують їх, можуть таким же чином обчислювати об'єкт. Because the property is stored in the database, all applications that read the property can evaluate the object in the same way. Додаткові відомості див. У розділі sp_addextendedproperty (Transact-SQL) . For more information, see sp_addextendedproperty (Transact-SQL) .

Щоб знайти базовий тип базового об'єкта синоніма, використовуйте функцію OBJECTPROPERTYEX. To find the base type of the base object of a synonym, use the OBJECTPROPERTYEX function. Додаткові відомості див. У розділі OBJECTPROPERTYEX (Transact-SQL) . For more information, see OBJECTPROPERTYEX (Transact-SQL) .

приклади Examples

У наступному прикладі буде повернутий базовий тип локального базового об'єкта синоніма. The following example returns the base type of a synonym's base object that is a local object.

USE tempdb; GO CREATE SYNONYM MyEmployee FOR AdventureWorks2012.HumanResources.Employee; GO SELECT OBJECTPROPERTYEX (OBJECT_ID ( 'MyEmployee'), 'BaseType') AS BaseType;

У наступному прикладі буде повернутий базовий тип віддаленого базового об'єкта синоніма, де базовий об'єкт знаходиться на сервері Server1. The following example returns the base type of a synonym's base object that is a remote object located on a server named Server1.

EXECUTE sp_addlinkedserver Server1; GO CREATE SYNONYM MyRemoteEmployee FOR Server1.AdventureWorks2012.HumanResources.Employee; GO SELECT OBJECTPROPERTYEX (OBJECT_ID ( 'MyRemoteEmployee'), 'BaseType') AS BaseType; GO

Див. Також Related Content

створення синонімів Create Synonyms
CREATE SYNONYM (Transact-SQL) CREATE SYNONYM (Transact-SQL)
DROP SYNONYM (Transact-SQL) DROP SYNONYM (Transact-SQL)

Новости