Oracle добавить комментарий к столбцу
Есть ли синтаксис комментария столбца, который позволяет мне указать комментарий столбца непосредственно, где я объявляю столбец в инструкции create table (т.е. inline)? 11g spec ничего не упоминает, на другой странице что-то упоминается, но я не мог заставить его работать. Существует способ указать комментарии после создания таблицы, но я думаю, что это раздражает, что комментарий отделен от определения поля. Я ищу что-то вроде этого (что не работает):
Переименование колонки
Переименуем колонку birthday в bd :
Comments Within SQL Statements
Comments can make your application easier for you to read and maintain. For example, you can include a comment in a statement that describes the purpose of the statement within your application. With the exception of hints, comments within SQL statements do not affect the statement execution. Refer to Hints on using this particular form of comment.
A comment can appear between any keywords, parameters, or punctuation marks in a statement. You can include a comment in a statement in two ways:
Begin the comment with a slash and an asterisk (/*). Proceed with the text of the comment. This text can span multiple lines. End the comment with an asterisk and a slash (*/). The opening and terminating characters need not be separated from the text by a space or a line break.
Begin the comment with -- (two hyphens). Proceed with the text of the comment. This text cannot extend to a new line. End the comment with a line break.
Some of the tools used to enter SQL have additional restrictions. For example, if you are using SQL*Plus, by default you cannot have a blank line inside a multiline comment. For more information, refer to the documentation for the tool you use as an interface to the database.
A SQL statement can contain multiple comments of both styles. The text of a comment can contain any printable characters in your database character set.
These statements contain many comments:
Изменение типа данных колонки
Изменим тип колонки dept_id с числового на строковый:
Здесь нужно обратить внимание на то, что при изменении типа мы не добавляли NOT NULL . В MODIFY мы должны указать действия, которые действительно что-то изменят. Колонка dept_id и так была not null , и при изменении типа это свойство не нужно указывать.
Если попробовать добавить not null , получим ошибку ORA-01442: column to be modified to NOT NULL is already NOT NULL :
Следует учитывать одну важную деталь при изменении типа данных - изменяемая колонка должна быть пуста.
Рассмотрим более подробно процесс изменения типа колонки, если в ней уже содержатся данные.
Спустя какое-то время мы решили, что не хотим использовать числовое поле для boolean значений. Вместо этого было решено использовать более понятный строковый тип.
Итак, для начала добавим колонку с нужным нам типом данных. Так как мы не можем назвать ее notify_by_email (такая уже есть на данный момент), то назовем ее notify_by_email_new :
После этого нужно заполнить эту колонку данными. Алгоритм прост - значение “1” в колонке notify_by_email должно быть перенесено как значение “Y” в колонку notify_by_email_new , а значение “0” нужно перенести в виде “N”. Так как при добавлении колонки мы указали значение по-умолчанию, то в таблице каждая строка содержит значение “N” в этой колонке. Все, что осталось - это изменить значение на “Y”, где notify_by_email равен 1:
Затем удаляем колонку notify_by_email :
Теперь можно переименовать notify_by_email_new в notify_by_email :
Смотрим на результат:
ОТВЕТЫ
Ответ 1
Я боюсь, что "раздражающий" COMMENT ON синтаксис - единственный способ сделать это. SQL Server, PostgreSQL и DB2 используют один и тот же синтаксис (хотя, насколько мне известно, не существует стандартного синтаксиса ANSI для добавления комментариев к объектам базы данных).
MySQL поддерживает способ работы. Я согласен, что это был бы более хороший механизм, но по моему опыту мало кто использует комментарии вообще, что я сомневаюсь, что Oracle когда-нибудь изменит его.
Ответ 2
Я боюсь, что это можно сделать только после создания таблицы, используя синтаксис comment on column . is '' .
Ответ 3
Обходной путь к этому раздражающему синтаксису - также просмотр и редактирование таблиц в Oracles SQLExplorer. Он содержит мастер, который позволяет редактировать комментарии рядом с столбцами. Это даже позволяет легко создавать скрипты alter table.
Моя процедура при редактировании таблиц заключается в том, чтобы вводить изменения в мастере без их фактического выполнения, затем перейдите на вкладку DDL и извлеките SQL оттуда (как обновление, а не полное создание script) и нажмите cancel on Мастер. Затем я помещаю созданный SQL в SQL script, который я пишу. Только когда я закончил с script, я все выполнил; Я не делаю никаких изменений с самим мастером.
Ответ 4
Тест на sqlplus (или аналогичный), но синтаксис выглядит следующим образом:
Обратите внимание, что комментарий будет отображаться в SQLDeveloper (или Toad или независимо от того, что у вас есть), пока вы не откроете указанные свойства таблицы.
Я понимаю, что подобный синтаксис существует для MySQL и других, но он не является правильным ANSI. Это очень полезно.
Use the COMMENT statement to add a comment about a table, view, materialized view, or column into the data dictionary.
To drop a comment from the database, set it to the empty string ' '.
"Comments" for more information on associating comments with SQL statements and schema objects
Oracle Database Reference for information on the data dictionary views that display comments
The object about which you are adding a comment must be in your own schema or:
To add a comment to a table, view, or materialized view, you must have COMMENT ANY TABLE system privilege.
To add a comment to an indextype, you must have the CREATE ANY INDEXTYPE system privilege.
To add a comment to an operator, you must have the CREATE ANY OPERATOR system privilege.
Specify the schema and name of the table or materialized view to be commented. If you omit schema , then Oracle Database assumes the table or materialized view is in your own schema.
In earlier releases, you could use this clause to create a comment on a materialized view. You should now use the COMMENT ON MATERIALIZED VIEW clause for materialized views.
Specify the name of the column of a table, view, or materialized view to be commented. If you omit schema , then Oracle Database assumes the table, view, or materialized view is in your own schema.
You can view the comments on a particular table or column by querying the data dictionary views USER_TAB_COMMENTS , DBA_TAB_COMMENTS , or ALL_TAB_COMMENTS or USER_COL_COMMENTS , DBA_COL_COMMENTS , or ALL_COL_COMMENTS .
Specify the name of the operator to be commented. If you omit schema , then Oracle Database assumes the operator is in your own schema.
You can view the comments on a particular operator by querying the data dictionary views USER_OPERATOR_COMMENTS , DBA_OPERATOR_COMMENTS , or ALL_OPERATOR_COMMENTS .
Specify the name of the indextype to be commented. If you omit schema , then Oracle Database assumes the indextype is in your own schema.
You can view the comments on a particular indextype by querying the data dictionary views USER_INDEXTYPE_COMMENTS , DBA_INDEXTYPE_COMMENTS , or ALL_INDEXTYPE_COMMENTS .
MATERIALIZED VIEW Clause
Specify the name of the materialized view to be commented. If you omit schema , then Oracle Database assumes the materialized view is in your own schema.
You can view the comments on a particular materialized view by querying the data dictionary views USER_MVIEW_COMMENTS , DBA_MVIEW_COMMENTS , or ALL_MVIEW_COMMENTS .
Specify the text of the comment. Please refer to "Text Literals" for a syntax description of 'string' .
Creating Comments: Example To insert an explanatory remark on the job_id column of the employees table, you might issue the following statement:
You can create two types of comments:
Comments within SQL statements are stored as part of the application code that executes the SQL statements.
Comments associated with individual schema or nonschema objects are stored in the data dictionary along with metadata on the objects themselves.
Подготовка данных
Тестировать будем на таблице employees . Изначально она будет состоять только из одной колонки id :
Переименование таблицы
Следующий запрос переименует таблицу employees в emps :
Стоит отметить, что переименование таблицы не приведет к ошибке при наличии ссылок на нее. В нашем примере таблица успешно переименуется, несмотря на дочернюю таблицу emp_bonuses . Внешний ключ при этом никуда не девается, в таблицу emp_bonuses по-прежнему нельзя добавить значения, нарушающие условия внешнего ключа.
Comments on Schema and Nonschema Objects
You can use the COMMENT command to associate a comment with a schema object (table, view, materialized view, operator, indextype, mining model) or a nonschema object (edition) using the COMMENT command. You can also create a comment on a column, which is part of a table schema object. Comments associated with schema and nonschema objects are stored in the data dictionary. Refer to COMMENT for a description of this form of comment.
Изменение атрибута NOT NULL в колонке
Сделаем так, чтобы в колонку dept_id можно было сохранять null :
А теперь снова сделаем ее NOT NULL :
Нельзя изменить колонку на NOT NULL, если в ней уже содержатся NULL-значения.
Удаление нескольких колонок в таблице
Удалим колонки emp_firstname и is_out из таблицы:
Удалять все колонки из таблицы нельзя, получим ошибку ORA-12983: cannot drop all columns in a table .
Hints
Hints are comments in a SQL statement that pass instructions to the Oracle Database optimizer. The optimizer uses these hints to choose an execution plan for the statement, unless some condition exists that prevents the optimizer from doing so.
Hints were introduced in Oracle7, when users had little recourse if the optimizer generated suboptimal plans. Now Oracle provides a number of tools, including the SQL Tuning Advisor, SQL plan management, and SQL Performance Analyzer, to help you address performance problems that are not solved by the optimizer. Oracle strongly recommends that you use those tools rather than hints. The tools are far superior to hints, because when used on an ongoing basis, they provide fresh solutions as your data and database environment change.
Hints should be used sparingly, and only after you have collected statistics on the relevant tables and evaluated the optimizer plan without hints using the EXPLAIN PLAN statement. Changing database conditions as well as query performance enhancements in subsequent releases can have significant impact on how hints in your code affect performance.
The remainder of this section provides information on some commonly used hints. If you decide to use hints rather than the more advanced tuning tools, be aware that any short-term benefit resulting from the use of hints may not continue to result in improved performance over the long term.
A statement block can have only one comment containing hints, and that comment must follow the SELECT , UPDATE , INSERT , MERGE , or DELETE keyword.
The following syntax diagram shows hints contained in both styles of comments that Oracle supports within a statement block. The hint syntax must follow immediately after an INSERT , UPDATE , DELETE , SELECT , or MERGE keyword that begins the statement block.
The plus sign (+) causes Oracle to interpret the comment as a list of hints. The plus sign must follow immediately after the comment delimiter. No space is permitted.
hint is one of the hints discussed in this section. The space between the plus sign and the hint is optional. If the comment contains multiple hints, then separate the hints by at least one space.
string is other commenting text that can be interspersed with the hints.
The --+ syntax requires that the entire comment be on a single line.
Oracle Database ignores hints and does not return an error under the following circumstances:
The hint contains misspellings or syntax errors. However, the database does consider other correctly specified hints in the same comment.
The comment containing the hint does not follow a DELETE , INSERT , MERGE , SELECT , or UPDATE keyword.
A combination of hints conflict with each other. However, the database does consider other hints in the same comment.
The database environment uses PL/SQL version 1, such as Forms version 3 triggers, Oracle Forms 4.5, and Oracle Reports 2.5.
A global hint refers to multiple query blocks. Refer to Specifying Multiple Query Blocks in a Global Hint for more information.
With 19c you can use DBMS_XPLAN to find out whether a hint is used or not used. For more information, see the Database SQL Tuning Guide .
Specifying a Query Block in a Hint
You can specify an optional query block name in many hints to specify the query block to which the hint applies. This syntax lets you specify in the outer query a hint that applies to an inline view.
The syntax of the query block argument is of the form @ queryblock , where queryblock is an identifier that specifies a query block in the query. The queryblock identifier can either be system-generated or user-specified. When you specify a hint in the query block itself to which the hint applies, you omit the @queryblock syntax.
The system-generated identifier can be obtained by using EXPLAIN PLAN for the query. Pretransformation query block names can be determined by running EXPLAIN PLAN for the query using the NO_QUERY_TRANSFORMATION hint. See NO_QUERY_TRANSFORMATION Hint.
The user-specified name can be set with the QB_NAME hint. See QB_NAME Hint.
Specifying Global Hints
Many hints can apply both to specific tables or indexes and more globally to tables within a view or to columns that are part of indexes. The syntactic elements tablespec and indexspec define these global hints .
You must specify the table to be accessed exactly as it appears in the statement. If the statement uses an alias for the table, then use the alias rather than the table name in the hint. However, do not include the schema name with the table name within the hint, even if the schema name appears in the statement.
Specifying a global hint using the tablespec clause does not work for queries that use ANSI joins, because the optimizer generates additional views during parsing. Instead, specify @ queryblock to indicate the query block to which the hint applies.
When tablespec is followed by indexspec in the specification of a hint, a comma separating the table name and index name is permitted but not required. Commas are also permitted, but not required, to separate multiple occurrences of indexspec .
Specifying Multiple Query Blocks in a Global Hint
Oracle Database ignores global hints that refer to multiple query blocks. To avoid this issue, Oracle recommends that you specify the object alias in the hint instead of using tablespec and indexspec .
For example, consider the following view v and table t :
The following examples use the EXPLAIN PLAN statement, which enables you to display the execution plan and determine if a hint is honored or ignored. Refer to EXPLAIN PLAN for more information.
The LEADING hint is ignored in the following query because it refers to multiple query blocks, that is, the main query block containing table t and the view query block v :
The following SELECT statement returns the execution plan, which shows that the LEADING hint was ignored:
The LEADING hint is honored in the following query because it refers to object aliases, which can be found in the execution plan that was returned by the previous query:
The following SELECT statement returns the execution plan, which shows that the LEADING hint was honored:
Hints by Functional Category
Table 2-23 lists the hints by functional category and contains cross-references to the syntax and semantics for each hint. An alphabetical reference of the hints follows the table.
есть ли синтаксис комментария столбца, который позволяет мне указать комментарий столбца непосредственно, где я объявляю столбец в инструкции create table (т. е. inline)? The 11г спецификаций ничего не упоминает, on другая страница что-то, но я не мог заставить его работать. Есть способ укажите комментарии после создания таблицы, но я думаю, что это раздражает, что комментарий отделяется от определения поля. Я ищу что-то вроде этого (что не работает):
боюсь, что "раздражает" COMMENT ON синтаксис-это единственный способ сделать это. SQL Server, PostgreSQL и DB2 используют один и тот же синтаксис (хотя, насколько мне известно, нет стандартного синтаксиса ANSI для добавления комментариев к объектам базы данных).
MySQL поддерживает то, как вы хотели бы, чтобы он работал. Я согласен, что это был бы более приятный механизм, но по моему опыту так мало людей используют комментарии вообще, что я сомневаюсь, что Oracle когда-либо изменит его.
боюсь, это можно сделать только после создания таблицы, используя comment on column . is '' синтаксис.
обходным путем для этого раздражающего синтаксиса также является просмотр и редактирование таблиц в Oracles SQLExplorer. Он содержит мастер, который позволяет редактировать комментарии рядом со столбцами. Он даже позволяет легко создавать сценарии alter table.
моя процедура при редактировании таблиц заключается в вводе изменений в Мастере без их фактического выполнения, а затем перейдите к его DDL tab и получить SQL оттуда (как обновление, а не полный сценарий создания) и нажмите "Отмена" в Мастере. Затем я помещаю созданный SQL в сценарий SQL, который я пишу. Только когда я заканчиваю со скриптом, я выполняю все; я никогда не делаю никаких изменений с самим мастером.
тест на sqlplus( или аналогичный), но синтаксис выглядит следующим образом:
обратите внимание, что комментарий теперь будет отображаться в SQLDeveloper (или жабе или любом другом env), пока вы не откроете свойства указанной таблицы.
Я понимаю, что подобный синтаксис существует для MySQL и другим, но это не настоящий Анси. Но это очень полезно.
Уже созданные таблицы можно изменять. Для этого используется команда SQL ALTER . Данная команда относится к группе DDL.
Логическое удаление колонок
Удаление колонок в очень больших таблицах может занять достаточно большое количество времени. В таких случаях можно для начала пометить нужные колонки как неиспользуемые:
После выполнения данной команды Oracle удалит эти колонки логически, попросту пометив их как неиспользуемые. При запросе из таблицы они не будут видны, и в таблицу можно даже добавлять колонки с такими же названиями.
Чтобы удалить неиспользуемые колонки физически, используется следующий запрос:
Конечно, выполнять его желательно во время наименьшей нагрузки на сервер.
Добавление колонки в таблицу
Добавим в таблицу сотрудников колонку для хранения дня рождения:
По умолчанию все строки таблицы будут иметь null в новой колонке. Но если при ее добавлении указать значение по-умолчанию, то все строки будут содержать его в новой колонке.
Добавим колонку notify_by_email , которая будет по-умолчанию содержать в себе “1”, если сотруднику нужно отправлять уведомления по почте, и “0”, если нет:
Посмотрим, как сейчас выглядят данные в таблице:
Как видно, каждая строка содержит “0” в колонке notify_by_email .
Нельзя добавить колонку NOT NULL в таблицу с данными без значения по-умолчанию.
В результате получим ошибку ORA-01758: table must be empty to add mandatory (NOT NULL) column .
Но если указать значение по-умолчанию, ошибки не будет:
Колонка добавляется без ошибок:
Добавление нескольких колонок в таблицу
Чтобы добавить несколько колонок в таблицу, нужно просто перечислить их через запятую:
Удаление колонки из таблицы
Удалим только что добавленную колонку emp_lastname из таблицы:
Следует учитывать, что если на удаляемую колонку ссылаются строки из другой таблицы(посредством внешнего ключа), то удалить колонку не получится.
Убедимся в этом, создав таблицу emp_bonuses , которая будет ссылаться на колонку id в таблице employees :
Теперь попробуем удалить колонку id :
В результате мы получим ошибку ORA-12992: cannot drop parent key column , которая говорит о том, что удаляемая колонка является родительской для другой таблицы.
Читайте также: