SQL комментарии
В этом учебном материале вы узнаете, как использовать комментарии в выражениях SQL с синтаксисом и примерами.
Описание
В SQL вы можете комментировать свой код, как и любой другой язык. Комментарии могут появляться в одной строке или занимать несколько строк. Давайте рассмотрим, как комментировать ваши операторы SQL.
Синтаксис
Есть два синтаксиса, которые вы можете использовать для создания комментария в SQL.
Синтаксис использования символов — (два тире)
Синтаксис для создания комментария в SQL с использованием символов — .
— здесь пишется комментарий
Комментарий, начинающийся с символов — , должен находиться в конце строки в вашем операторе SQL с разрывом строки после него. Этот метод комментирования может занимать только одну строку в вашем SQL и должен находиться в конце строки.
Синтаксис использования символов /* и */
Синтаксис для создания комментария в SQL с использованием символов /* и */ .
/* здесь пишется комментарий */
Комментарий, который начинается с символа /* и заканчивается */ и может находиться в любом месте вашего SQL оператора. Этот метод комментирования может занимать несколько строк в вашем SQL.
Пример комментария в одной строку
Рассмотрим пример комментария в SQL, который находится на одной строке.
Например.
Вот комментарий, который появляется в SQL в отдельной строке.
Комментарии в SQL
Примечание:
Во всех статьях текущей категории уроков по SQL используются примеры и задачи, основанные на учебной базе данных.
Приступая к изучению данного материала, рекомендуется ознакомиться с описанием учебной БД.
Когда пользователь работает с большим количеством запросов или пишет их для третьих лиц, либо запросы имеют достаточно сложную логику, то в SQL-коде желательно использовать комментарии, вставляя их непосредственно в запрос.
Комментарии могут быть двух типов: однострочные и многострочные. В зависимости от типа применяется различный синтаксис. Однострочные начинаются с сочетания двух тире (—) и продолжаются до конца строки. Многострочные комментарии начинаются с сочетания символов слеша и звездочки (/*) и заканчиваются ими же, но в другой последовательности (*/).
Синтаксис комментариев зависит от системы, к которой выполняется запрос. Приведенные выше примеры подходят для систем MS SQL Server и Oracle, являющимися самыми распространенными.
Найдите комментарии в следующем SQL-коде и выполните его на учебной базе данных:
SQL: Comments
This SQL tutorial explains how to use comments within your SQL statements with syntax and examples.
Description
In SQL, you can comment your code just like any other language. Comments can appear on a single line or span across multiple lines. Let’s explore how to comment your SQL statements.
Syntax
There are two syntaxes that you can use to create a comment in SQL.
Syntax Using — symbol
The syntax for creating a comment in SQL using — symbol is:
A comment started with — symbol must be at the end of a line in your SQL statement with a line break after it. This method of commenting can only span a single line within your SQL and must be at the end of the line.
Syntax Using /* and */ symbols
The syntax for creating a comment in SQL using /* and */ symbols is:
A comment that starts with /* symbol and ends with */ and can be anywhere in your SQL statement. This method of commenting can span several lines within your SQL.
Example — Comment on a Single Line
Let’s look at an example that shows how to create a comment in SQL that is on a single line.
Here is a comment that appears on its own line in SQL:
Here is a comment that appears in the middle of the line in SQL:
Here is a comment that appears at the end of the line in SQL:
Example — Comment on Multiple Lines
You can also create a comment that spans multiple lines in your SQL statement.
This comment spans across multiple lines in SQL and in this example, it spans across 4 lines.
You can also create a comment that spans multiple lines using this syntax:
SQL will assume that everything after the /* symbol is a comment until it reaches the */ symbol, even if it spans multiple lines within the SQL statement. So in this example, the comment will span across 2 lines.
How to give comments in SQL
I am working in SQL. What is the complete explanation for using comments in SQL, with some example code?
5 Answers 5
MySQL Server supports three comment styles:
From a # character to the end of the line.
From a — sequence to the end of the line. In MySQL, the “— ” (double-dash) comment style requires the second dash to be followed by at least one whitespace or control character (such as a space, tab, newline, and so on). This syntax differs slightly from standard SQL comment syntax, as discussed in Section 1.8.2.5, “’—‘ as the Start of a Comment”.
From a /* sequence to the following */ sequence, as in the C programming language. This syntax enables a comment to extend over multiple lines because the beginning and closing sequences need not be on the same line.
In Oracle, there are three ways.
1.
2.
3.
The difference between REM and the other two is that, — and /* */ can be used in a PL/SQL block, while REM[ARK] cannot.
So, — and /* */ works in PL/SQL block too. However, REM won’t.
Update Mostly all GUI based tools are able to execute SQL*Plus commands in their own sqlplus type window. It works perfectly in SQL Developer when executed as a script . In PL/SQL Developer too it should work with COMMAND window.
A screenshot from SQL Developer .
Same in SQL*Plus .
You can write a comment in SQL & PLSQL statements in two easy ways:
Begin the comment section with a forward slash and an asterisk (/*). Proceed with the text of the comment. This text can be spanning multiple lines.
Begin the comment section with — (two hyphens). Proceed with the text of the comment. This text cannot extend to a new line for new commenting. Every line start with – (two hyphens). Let see below examples
SELECT e.ename /* Author: OnlinteItTutor.com */ FROM emp e;
Here is a SQL comment in query that appears in the middle of the line:
Here is a SQL comments in query that appears at the end of the line:
In Oracle, you can create a SQL comment that shows multiple lines in your SQL statement. For example:
This SQL comment in query shows across multiple lines in Oracle — in this example, it shows across 4 lines. In Oracle, you can also create a SQL comment in query that spans multiple lines using this syntax: