Перейти к содержимому

Как закомментировать код в sql

  • автор:

Комментарии в SQL

Примечание:
Во всех статьях текущей категории уроков по SQL используются примеры и задачи, основанные на учебной базе данных.

Приступая к изучению данного материала, рекомендуется ознакомиться с описанием учебной БД.

Когда пользователь работает с большим количеством запросов или пишет их для третьих лиц, либо запросы имеют достаточно сложную логику, то в SQL-коде желательно использовать комментарии, вставляя их непосредственно в запрос.

Комментарии могут быть двух типов: однострочные и многострочные. В зависимости от типа применяется различный синтаксис. Однострочные начинаются с сочетания двух тире (—) и продолжаются до конца строки. Многострочные комментарии начинаются с сочетания символов слеша и звездочки (/*) и заканчиваются ими же, но в другой последовательности (*/).

Синтаксис комментариев зависит от системы, к которой выполняется запрос. Приведенные выше примеры подходят для систем MS SQL Server и Oracle, являющимися самыми распространенными.

Найдите комментарии в следующем SQL-коде и выполните его на учебной базе данных:

SQL comments

SQL comments

SQL comments – In SQL you can comment on your code like any other language. Comments can appear in one line or take up several lines. Let’s take a look at how to comment on your SQL statements.

SQL comments Syntax

There are two syntaxes that you can use to create a comment in SQL.

< h3>Syntax for character use — (two dashes)

Syntax for creating a comment in SQL using symbols –.

— this is where the comment is written.

A comment starting with — should be at the end of a line in your SQL statement with a line break after it. This comment method can only take up one line in your SQL and should be at the end of the line.

The syntax for using /* and */ characters

Syntax for creating a comment in SQL using characters /* and */.

/* comment is written here */.

A comment that starts with /* and ends with */ and can be found anywhere in your SQL statement. This method of commenting can take several lines in your SQL statement.

Comment on a single line

Let’s consider an example of a comment in SQL, which is on one line. For example.

Here is a comment that appears in SQL on a separate line.

SELECT webs.site_name
/* Author: Mickolai */
FROM webs;

Here is the comment that appears in the middle of the line in SQL.

SELECT /* Author: Mickolai */ webs.site_name
FROM webs;

Here is the comment that appears at the end of the line in SQL.

SELECT webs.site_name /* Author: Mickolai */
FROM webs;

or:

SELECT webs.site_name — Author: Mickolai
FROM webs;

A comment for several lines

You can also create a comment that takes several lines in your SQL statement.
For example.

SELECT webs.site_name
/*
* Author: Mickolai
* Purpose: To show a comment that takes several lines in your SQL statement.
*/
FROM webs;

This comment covers several lines in SQL, and in this example 4 lines.
You can also create a comment that takes several lines using this syntax.

SELECT webs.site_name /* Author: Mickolai
Purpose: To show a comment that takes several lines in your SQL statement. */
FROM webs;

SQL will assume that everything after the /* character is a comment until it reaches the */ character, even if it takes several lines in the SQL statement. Thus, in this example, the comment will occupy 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?

Peter Mortensen's user avatar

vijaya g's user avatar

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 .

enter image description here

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:

SQL комментарии

В этом учебном материале вы узнаете, как использовать комментарии в выражениях SQL с синтаксисом и примерами.

Описание

В SQL вы можете комментировать свой код, как и любой другой язык. Комментарии могут появляться в одной строке или занимать несколько строк. Давайте рассмотрим, как комментировать ваши операторы SQL.

Синтаксис

Есть два синтаксиса, которые вы можете использовать для создания комментария в SQL.
Синтаксис использования символов — (два тире)

Синтаксис для создания комментария в SQL с использованием символов — .

— здесь пишется комментарий

Комментарий, начинающийся с символов — , должен находиться в конце строки в вашем операторе SQL с разрывом строки после него. Этот метод комментирования может занимать только одну строку в вашем SQL и должен находиться в конце строки.

Синтаксис использования символов /* и */

Синтаксис для создания комментария в SQL с использованием символов /* и */ .
/* здесь пишется комментарий */
Комментарий, который начинается с символа /* и заканчивается */ и может находиться в любом месте вашего SQL оператора. Этот метод комментирования может занимать несколько строк в вашем SQL.

Пример комментария в одной строку

Рассмотрим пример комментария в SQL, который находится на одной строке.
Например.
Вот комментарий, который появляется в SQL в отдельной строке.

Добавить комментарий

Ваш адрес email не будет опубликован. Обязательные поля помечены *