After reading my previous article about SEQUENCE one of my friend asked a question about the performance of using Sequence for quick and continuous generation and whether there is a way to create and manage this using Management Studio ?
Yes, SEQUENCE support CACHE option
- /* Create Sequence with Cache */
- CREATE SEQUENCE RunningNumbers
- As INT
- MINVALUE 1
- NO MAXVALUE
- START WITH 1
- CACHE 500
- NO CYCLE;
Using CACHE option, you can specify how many values should be pre generated and available ready, you can set the cache size based on your application’ requirement.
Default cache size is 20
To use in Loop for quick processing
To get a range of numbers to use in a loop, you can use sp_sequence_get_range System stored procedure, so that you can get a range and not have to use NEXT VALUE option for each loop call
- /* Get Range of Numbers using Sequence */
- @RANGE_FIRST_VALUE SQL_VARIANT,
- @RANGE_LAST_VALUE SQL_VARIANT,
- @RANGE_CYCLE_COUNT INT,
- @SEQUENCE_INCREMENT SQL_VARIANT,
- @SEQUENCE_MIN_VALUE SQL_VARIANT,
- @SEQUENCE_MAX_VALUE SQL_VARIANT;
- EXEC sp_sequence_get_range
- @sequence_name = 'RunningNumbers',
- @range_size = 15,
- @range_first_value = @range_first_value OUTPUT,
- @range_last_value = @range_last_value OUTPUT,
- @range_cycle_count = @range_cycle_count OUTPUT,
- @sequence_increment = @sequence_increment OUTPUT,
- @sequence_min_value = @sequence_min_value OUTPUT,
- @sequence_max_value = @sequence_max_value OUTPUT;
- 'RunningNumbers' AS [Sequence Name],
- @range_first_value AS [Sequence First Value],
- @range_last_value AS [Sequence Last Value],
- @range_cycle_count AS [Range Cycle Count],
- @sequence_increment AS [Sequence Increment],
- @sequence_min_value AS [Sequence Min Value],
- @sequence_max_value AS [Sequence Max Value];
You can use [Sequence First Value] and [Sequence Last Value] and use it in your loop to insert data.
How to create and manage SEQUENCE from Management Studio ?
Step 1 : Open SQL Server “Denali” Management Studio, and connect to SQL Server “Denali” instance and go to your database in Object Explorer
Step 2: Expand “Programmability” and then expand "Sequences" to currently available ones
Step 3: To create a new sequence, right click on Sequence and click on “New Sequence”
Step 4: Specify the name and other required options such as Start Value, Increment By, etc.. and click “Ok” to create Sequence
Step 5: To modify the Sequence, right click on the selected sequence and click “Properties”
If you see the above screenshot, you might notice that Data Type, Precision or name of sequence can not be modified. You can change the other values, similarly you will see an option to restart the sequence as well.
Note: To rename you can use the “Rename” option in Context menu.
Step 6: To drop the sequence, right click on the selected sequence and click “Delete”
Let me know your experiences and feedback about SEQUENCEs