Что такое sequence в sql

Объект SEQUENCE (последовательность) в Microsoft SQL Server

Всем привет! Сегодня мы поговорим про объект SEQUENCE (последовательность) в Microsoft SQL Server, Вы узнаете, что такое SEQUENCE, для чего этот объект нужен, какие у него особенности, и, конечно же, научитесь им пользоваться (создавать, изменять, удалять и использовать).

Что такое sequence в sql. Смотреть фото Что такое sequence в sql. Смотреть картинку Что такое sequence в sql. Картинка про Что такое sequence в sql. Фото Что такое sequence в sql

SEQUENCE в Microsoft SQL Server

SEQUENCE – это объект SQL Server, который генерирует числовые значения в определенной последовательности в соответствии с заданной спецификацией.

В числе основных предназначений SEQUENCE является формирования значений для столбца идентификаторов в таблицах.

В Microsoft SQL Server SEQUENCE, как объект, появился только в 2012 версии, ранее для формирования значений столбцов идентификаторов в таблицах использовалось свойство IDENTITY. Теперь для этих целей можно использовать и IDENTITY, и SEQUENCE, в чем их отличие я подробно расскажу в следующих материалах.

SEQUENCE – это пользовательский объект, т.е. последовательность создают пользователи точно так же, как и другие объекты: хранимые процедуры, функции и так далее. Для создания последовательности требуются соответствующие разрешения, например, CREATE SEQUENCE. А члены предопределенных ролей db_owner и db_ddladmin по умолчанию могут выполнять любые операции с последовательностями.

Последовательность числовых значений в Microsoft SQL Server может формироваться в возрастающем или убывающем порядке с заданным интервалом. Кроме того, можно настроить перезапуск (т.е. зацикливание) последовательности, когда она исчерпана, а также задать минимальное и максимальное значения последовательности.

Значение последовательности получают с помощью вызова функции NEXT VALUE FOR, которое возвращает одно значение, однако можно получить сразу несколько значений за один раз, это делается с помощью системной процедуры sp_sequence_get_range.

SEQUENCE можно изменить уже после создания, так же, как и другие объекты, это делается с помощью инструкции ALTER SEQUENCE.

Еще одной особенностью SEQUENCE является то, что в своей работе она использует кэширование, что повышает производительность для приложений, которые используют последовательность. Это достигается за счет того, что значения последовательности заранее создаются и хранятся в памяти, а при обращении к SEQUENCE за новым значением это значение возвращается из памяти, тем самым значительно уменьшается число операций дискового ввода-вывода, которые требуются для создания значений последовательности.

Управляется кэширование последовательности с помощью параметра CACHE, который по умолчанию включен. Для его отключения необходимо указать NO CACHE.

Посмотреть, какие последовательности есть в базе данных и получить все сопутствующие сведения о последовательностях (параметры, с которыми они создавались), Вы можете с помощью обращения к системному представлению sys.sequences.

Синтаксис SEQUENCE

Описание синтаксиса

ПараметрОписание
CREATE SEQUENCEИнструкция создания объектов последовательности.
schema_name и sequence_nameИмя схемы и имя последовательности.
valueЗначение параметра.
ASТип данных значения, которое будет возвращать последовательность. Допускаются только целочисленные значения: TINYINT, SMALLINT, INT, BIGINT или NUMERIC с масштабом 0. Более подробно о типах данных можете посмотреть в отдельном материале – Типы данных в T-SQL (Microsoft SQL Server). Если тип данных не указан, то по умолчанию используется BIGINT.
START WITHНачальное значение, возвращаемое объектом последовательности. Это значение должно быть не больше максимального и не меньше минимального значения объекта последовательности. По умолчанию начальным значением у возрастающей последовательности является минимально возможное значение, а для убывающей последовательности – максимально возможное.
INCREMENT BYЗначение, на которое увеличивается (или уменьшается) значение объекта последовательности.
Если данное значение отрицательное, то объект последовательности убывает, если положительное, то возрастает.
По умолчанию используется значение 1. Данное значение не может быть равно 0.
MINVALUEМинимальное значение объекта последовательности.
По умолчанию минимальным значением для новой последовательности является минимальное значение для типа данных этой последовательности. Обращаю внимание, что для всех типов данных, кроме tinyint, минимальное значение – это отрицательное число.
MAXVALUEМаксимальное значение объекта последовательности.
По умолчанию максимальным значением для последовательности является максимальное значение типа данных объекта последовательности.
CYCLEПараметр показывает, должна ли последовательность быть перезапущена, как только она достигнет своего максимального или минимального значения. По умолчанию используется параметр NO CYCLE.
CACHEПараметр, который управляет кэшированием значений объектов последовательности. По умолчанию имеет значение CACHE. Для отключения кэширования необходимо указать NO CACHE.

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

Примеры создания SEQUENCE в Microsoft SQL Server

Теперь давайте разберём, как создается последовательность в Microsoft SQL Server.
Для выполнения примеров у меня есть база данных Test, в которой я и буду создавать последовательность.

Заметка! Для комплексного изучения языка SQL и T-SQL рекомендую посмотреть мои видеокурсы по T-SQL, в которых используется последовательная методика обучения специально для начинающих.

Во всех примерах последовательность будет создаваться с названием TestSequence в схеме по умолчанию (dbo), поэтому в инструкциях я не буду указывать конкретное название схемы.

Источник

CREATE SEQUENCE

Последовательность CREATE SEQUENCE Oracle

Последовательность CREATE SEQUENCE – это объект базы данных, который генерирует целые числа в соответствии с правилами, установленными во время его создания. Для последовательности можно указывать как положительные, так и отрицательные целые числа. В системах баз данных последовательности применяют для самых разных целей, но в основном для автоматической генерации первичных ключей. Тем не менее к первичному ключу таблицы последовательность никак не привязана, так что в некотором смысле она является еще и объектом коллективного пользования. Если первичный ключ нужен лишь для обеспечения уникальности, а не для того, чтобы нести определенный смысл, последовательность является отличным средством.

Последовательность создается командой CREATE SEQUENCE.

CREATE SEQUENCE

Что такое sequence в sql. Смотреть фото Что такое sequence в sql. Смотреть картинку Что такое sequence в sql. Картинка про Что такое sequence в sql. Фото Что такое sequence в sql

Синтаксис команды CREATE SEQUENCE

Синтаксис команды CREATE SEQUENCE

Основные ключевые слова и параметры CREATE SEQUENCE:

Пример 1 CREATE SEQUENCE
Создание последовательности sequence_1.s Первое обращение к этой последовательности возвратит 1. Второе обращение возвратит 11. Каждое следующее обращение возвратит значение, на 10 большее предыдущего:

Пример 2 CREATE SEQUENCE
Создание последовательности sequence_2. Последовательность убывающая, циклическая, при достижении нуля последовательность вновь обращается к старшему числу. Такой последовательностью удобно пользоваться в тех программах, где до наступления некоторого события должен быть выполнен обратный отсчет:

CREATE SEQUENCE sequence_2
START WITH 20
INCREMENT BY –1
MAXVALUE 20
MINVALUE 0
CYCLE
ORDER
CACHE 2;

После создания последовательности к ней можно обращаться через псевдостолбцы CURRVAL (возвращает текущее значение последовательности) и NEXTVAL (выполняет приращение последовательности и возвращает ее следующее значение). Текущее и следующее значения последовательности пользователи базы данных получают, выполняя команду SELECT. Последовательности – не таблицы, а простые объекты, генерирующие целые числа с помощью виртуальных столбцов, поэтому нужна общедоступная таблица словаря данных DUAL, из которой будут извлекаться данные виртуальных столбцов.

Первое обращение к NEXTVAL возвращает начальное значение последовательности. Последующие обращения к NEXTVAL изменяют значение последовательности на приращение, которое было определено, и возвращают новое значение. Любое обращение к CURRVAL всегда возвращает текущее значение последовательности, а именно, то значение, которое было возвращено последним обращением к NEXTVAL. Прежде чем обращаться к CURRVAL в текущем сеансе работы, необходимо хотя бы один раз выполнить обращение к NEXTVAL.

В одном предложении SQL приращение последовательности может быть выполнено только один раз. Если предложение содержит несколько обращений к NEXTVAL для одной и той же последовательности, то ORACLE наращивает последовательность один раз, и возвращает одно и то же значение для всех вхождений NEXTVAL. Если предложение содержит обращения как к CURRVAL, так и к NEXTVAL, то ORACLE наращивает последовательность и возвращает одно и то же значение как для CURRVAL, так и для NEXTVAL, независимо от того, в каком порядке они встречаются в предложении.

К одной и той же последовательности могут обращаться одновременно несколько пользователей, без какого-либо ожидания или блокировки:

.CURRVAL

.NEXTVAL

Чтобы обратиться к текущему или следующему значению последовательности, принадлежащей схеме другого пользователя, пользователь должен иметь либо объектную привилегию SELECT по этой последовательности, либо системную привилегию SELECT ANY SEQUENCE, и должен дополнительно квалифицировать эту последовательность именем содержащей ее схемы:

Значения CURRVAL и NEXTVAL используются в следующих местах:

Нельзя использовать значения CURRVAL и NEXTVAL в следующих местах:

SELECT SEQUENCE. Пример 3.
Действие циклической последовательности sequence_2 при достижении ею значения MINVALUE:

SQL> SELECT sequence_2.NEXTVAL FROM dual;

NEXTVAL

SQL> SELECT sequence_2.NEXTVAL FROM dual;

NEXTVAL

SQL> SELECT sequence_2.NEXTVAL FROM dual;

NEXTVAL

SQL> SELECT sequence_2.NEXTVAL FROM dual;

NEXTVAL

SQL> SELECT sequence_2.NEXTVAL FROM dual;

NEXTVAL

CREATE SEQUENCE. Пример 4.
В следующем примере SEQUENCE после ссылки на столбец NEXVAL значение CURRVAL обновляется так, чтобы соответствовать значению NEXVAL, а предыдущее значение CURRVAL теряется:

SQL> SELECT sequence_2.CURRVAL FROM dual;

CURRVAL

SQL> SELECT sequence_2.NEXTVAL FROM dual;

NEXTVAL

SQL> SELECT sequence_2.NEXTVAL FROM dual;

NEXTVAL

SQL> SELECT sequence_2.NEXTVAL FROM dual;

NEXTVAL

SQL> SELECT sequence_2.CURRVAL FROM dual;

CURRVAL

CREATE SEQUENCE. Пример 5.
Ссылка на последовательности при изменении данных:

INSERT INTO emp VALUES (empseq.nextval, ‘LEWIS’, ‘CLERK’, 7902, SYSDATE, 1200, NULL, 20);
UPDATE emp SET deptno = empseq.currval WHERE ename = ‘Jones’

ALTER SEQUENCE. Пример 6.
Любой параметр последовательности можно изменить командой ALTER SEQUENCE. Новое значение вступает в силу немедленно. Все параметры последовательности, не указанные в команде ALTER SEQUENCE, остаются без изменений:

ALTER SEQUENCE sequence_2

INCREMENT BY –4;

Когда последовательность больше не нужна, ее можно удалить. Для этого администратор базы данных или владелец последовательности должен выполнить команду DROP SEQUENCE. В результате виртуальные столбцы последовательности NEXVAL и CURRVAL — переводятся в разряд неиспользуемых. Но, если последовательность применялась для генерации значений первичных ключей, созданные ею значения останутся в базе данных. Каскадного удаления значений, сгенерированных последовательностью, при ее удалении не происходит.

DROP SEQUENCE. Пример 7.
Удаление последовательности SEQUENCE:

DROP SEQUENCE sequence_2

Вы должны войти, чтобы оставить комментарий.

Источник

Что такое sequence в sql

When a sequence number is generated, the sequence is incremented, independent of the transaction committing or rolling back. If two users concurrently increment the same sequence, then the sequence numbers each user acquires may have gaps, because sequence numbers are being generated by the other user. One user can never acquire the sequence number generated by another user. After a sequence value is generated by one user, that user can continue to access that value regardless of whether the sequence is incremented by another user.

Sequence numbers are generated independently of tables, so the same sequence can be used for one or for multiple tables. It is possible that individual sequence numbers will appear to be skipped, because they were generated and used in a transaction that ultimately rolled back. Additionally, a single user may not realize that other users are drawing from the same sequence.

After a sequence is created, you can access its values in SQL statements with the CURRVAL pseudocolumn, which returns the current value of the sequence, or the NEXTVAL pseudocolumn, which increments the sequence and returns the new value.

Pseudocolumns for more information on using the CURRVAL and NEXTVAL

«How to Use Sequence Values» for information on using sequences

ALTER SEQUENCE or DROP SEQUENCE for information on modifying or dropping a sequence

To create a sequence in your own schema, you must have the CREATE SEQUENCE system privilege.

To create a sequence in another user’s schema, you must have the CREATE ANY SEQUENCE system privilege.

Источник

CREATE SEQUENCE (Transact-SQL)

Creates a sequence object and specifies its properties. A sequence is a user-defined schema bound object that generates a sequence of numeric values according to the specification with which the sequence was created. The sequence of numeric values is generated in an ascending or descending order at a defined interval and can be configured to restart (cycle) when exhausted. Sequences, unlike identity columns, are not associated with specific tables. Applications refer to a sequence object to retrieve its next value. The relationship between sequences and tables is controlled by the application. User applications can reference a sequence object and coordinate the values across multiple rows and tables.

Unlike identity columns values that are generated when rows are inserted, an application can obtain the next sequence number without inserting the row by calling the NEXT VALUE FOR function. Use sp_sequence_get_range to get multiple sequence numbers at once.

For information and scenarios that use both CREATE SEQUENCE and the NEXT VALUE FOR function, see Sequence Numbers.

Что такое sequence в sql. Смотреть фото Что такое sequence в sql. Смотреть картинку Что такое sequence в sql. Картинка про Что такое sequence в sql. Фото Что такое sequence в sqlTransact-SQL Syntax Conventions

Syntax

To view Transact-SQL syntax for SQL Server 2014 and earlier, see Previous versions documentation.

Arguments

sequence_name
Specifies the unique name by which the sequence is known in the database. Type is sysname.

[ built_in_integer_type | user-defined_integer_type
A sequence can be defined as any integer type. The following types are allowed.

If no data type is provided, the bigint data type is used as the default.

START WITH
The first value returned by the sequence object. The START value must be a value less than or equal to the maximum and greater than or equal to the minimum value of the sequence object. The default start value for a new sequence object is the minimum value for an ascending sequence object and the maximum value for a descending sequence object.

INCREMENT BY
Value used to increment (or decrement if negative) the value of the sequence object for each call to the NEXT VALUE FOR function. If the increment is a negative value, the sequence object is descending; otherwise, it is ascending. The increment cannot be 0. The default increment for a new sequence object is 1.

[ MINVALUE | NO MINVALUE ]
Specifies the bounds for the sequence object. The default minimum value for a new sequence object is the minimum value of the data type of the sequence object. This is zero for the tinyint data type and a negative number for all other data types.

[ MAXVALUE | NO MAXVALUE
Specifies the bounds for the sequence object. The default maximum value for a new sequence object is the maximum value of the data type of the sequence object.

[ CYCLE | NO CYCLE ]
Property that specifies whether the sequence object should restart from the minimum value (or maximum for descending sequence objects) or throw an exception when its minimum or maximum value is exceeded. The default cycle option for new sequence objects is NO CYCLE.

Cycling a SEQUENCE restarts from the minimum or maximum value, not from the start value.

[ CACHE [ ] | NO CACHE ]
Increases performance for applications that use sequence objects by minimizing the number of disk IOs that are required to generate sequence numbers. Defaults to CACHE.

For example, if a cache size of 50 is chosen, SQL Server does not keep 50 individual values cached. It only caches the current value and the number of values left in the cache. This means that the amount of memory required to store the cache is always two instances of the data type of the sequence object.

If the cache option is enabled without specifying a cache size, the Database Engine will select a size. However, users should not rely upon the selection being consistent. Microsoft might change the method of calculating the cache size without notice.

When created with the CACHE option, an unexpected shutdown (such as a power failure) may result in the loss of sequence numbers remaining in the cache.

General Remarks

Sequence numbers are generated outside the scope of the current transaction. They are consumed whether the transaction using the sequence number is committed or rolled back. Duplicate validation only occurs once a record is fully populated. This can result in some cases where the same number is used for more than one record during creation, but then gets identified as a duplicate. If this occurs and other autonumber values have been applied to subsequent records, this can result in a gap between autonumber values and is expected behavior.

Cache management

To improve performance, SQL Server pre-allocates the number of sequence numbers specified by the CACHE argument.

For an example, a new sequence is created with a starting value of 1 and a cache size of 15. When the first value is needed, values 1 through 15 are made available from memory. The last cached value (15) is written to the system tables on the disk. When all 15 numbers are used, the next request (for number 16) will cause the cache to be allocated again. The new last cached value (30) will be written to the system tables.

If the Database Engine is stopped after you use 22 numbers, the next intended sequence number in memory (23) is written to the system tables, replacing the previously stored number.

After SQL Server restarts and a sequence number is needed, the starting number is read from the system tables (23). The cache amount of 15 numbers (23-38) is allocated to memory and the next non-cache number (39) is written to the system tables.

If the Database Engine stops abnormally for an event such as a power failure, the sequence restarts with the number read from system tables (39). Any sequence numbers allocated to memory (but never requested by a user or application) are lost. This functionality may leave gaps, but guarantees that the same value will never be issued two times for a single sequence object unless it is defined as CYCLE or is manually restarted.

The cache is maintained in memory by tracking the current value (the last value issued) and the number of values left in the cache. Therefore, the amount of memory used by the cache is always two instances of the data type of the sequence object.

Setting the cache argument to NO CACHE writes the current sequence value to the system tables every time that a sequence is used. This might slow performance by increasing disk access, but reduces the chance of unintended gaps. Gaps can still occur if numbers are requested using the NEXT VALUE FOR or sp_sequence_get_range functions, but then the numbers are either not used or are used in uncommitted transactions.

When a sequence object uses the CACHE option, if you restart the sequence object, or alter the INCREMENT, CYCLE, MINVALUE, MAXVALUE, or the cache size properties, it will cause the cache to be written to the system tables before the change occurs. Then the cache is reloaded starting with the current value (i.e. no numbers are skipped). Changing the cache size takes effect immediately.

CACHE option when cached values are available

The following process occurs every time that a sequence object is requested to generate the next value for the CACHE option if there are unused values available in the in-memory cache for the sequence object.

The next value for the sequence object is calculated.

The new current value for the sequence object is updated in memory.

The calculated value is returned to the calling statement.

CACHE option when the cache is exhausted

The following process occurs every time a sequence object is requested to generate the next value for the CACHE option if the cache has been exhausted:

The next value for the sequence object is calculated.

The last value for the new cache is calculated.

The system table row for the sequence object is locked, and the value calculated in step 2 (the last value) is written to the system table. A cache-exhausted xevent is fired to notify the user of the new persisted value.

NO CACHE option

The following process occurs every time that a sequence object is requested to generate the next value for the NO CACHE option:

The next value for the sequence object is calculated.

The new current value for the sequence object is written to the system table.

The calculated value is returned to the calling statement.

Metadata

For information about sequences, query sys.sequences.

Security

Permissions

Requires CREATE SEQUENCE, ALTER, or CONTROL permission on the SCHEMA.

Members of the db_owner and db_ddladmin fixed database roles can create, alter, and drop sequence objects.

Members of the db_owner and db_datawriter fixed database roles can update sequence objects by causing them to generate numbers.

The following example grants the user AdventureWorks\Larry permission to create sequences in the Test schema.

Ownership of a sequence object can be transferred by using the ALTER AUTHORIZATION statement.

If a sequence uses a user-defined data type, the creator of the sequence must have REFERENCES permission on the type.

Audit

To audit CREATE SEQUENCE, monitor the SCHEMA_OBJECT_CHANGE_GROUP.

Examples

For examples of creating sequences and using the NEXT VALUE FOR function to generate sequence numbers, see Sequence Numbers.

Most of the following examples create sequence objects in a schema named Test.

To create the Test schema, execute the following statement.

A. Creating a sequence that increases by 1

In the following example, Thierry creates a sequence named CountBy1 that increases by one every time that it is used.

B. Creating a sequence that decreases by 1

The following example starts at 0 and counts into negative numbers by one every time it is used.

C. Creating a sequence that increases by 5

The following example creates a sequence that increases by 5 every time it is used.

D. Creating a sequence that starts with a designated number

After importing a table, Thierry notices that the highest ID number used is 24,328. Thierry needs a sequence that will generate numbers starting at 24,329. The following code creates a sequence that starts with 24,329 and increments by 1.

E. Creating a sequence using default values

The following example creates a sequence using the default values.

Execute the following statement to view the properties of the sequence.

A partial list of the output demonstrates the default values.

OutputDefault value
start_value-9223372036854775808
increment1
mimimum_value-9223372036854775808
maximum_value9223372036854775807
is_cycling0
is_cached1
current_value-9223372036854775808

F. Creating a sequence with a specific data type

G. Creating a sequence using all arguments

The following example creates a sequence named DecSeq using the decimal data type, having a range from 0 to 255. The sequence starts with 125 and increments by 25 every time that a number is generated. Because the sequence is configured to cycle when the value exceeds the maximum value of 200, the sequence restarts at the minimum value of 100.

Execute the following statement to see the first value; the START WITH option of 125.

Execute the statement three more times to return 150, 175, and 200.

Execute the statement again to see how the start value cycles back to the MINVALUE option of 100.

Execute the following code to confirm the cache size and see the current value.

Источник

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

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