Home

Sequences

Introduction to Sequences

Overview

A sequence is a series of numbers that are continually generated and assigned to a column of a table. This works like an identity column. The difference is that, if you need an identity, you must create it in a column of a table and if you need the same type of identity on a column of another table, you must create the identity in the column of the other table. On the other hand, a sequence is a programmatic object, like a function, that you create at the database level and you can apply that sequence to any table you want.

Visually Creating a Sequence

To visually create a sequence, in the Object Explorer, expand the desired database and the Programmability nodes. Right-click Sequences and click New Sequence... This would present the New Sequence dialog box with some default (basic) values.

Programmatically Creating a Sequence

The Transact-SQL syntax to create a sequence is:

CREATE SEQUENCE [schema_name . ] sequence_name
    [ AS [ built_in_integer_type | user-defined_integer_type ] ]
    [ START WITH <constant> ]
    [ INCREMENT BY  <constant> ]
    [ { MINVALUE [  <constant> ] } | { NO MINVALUE } ]
    [ { MAXVALUE [  <constant> ] } | { NO MAXVALUE } ]
    [ CYCLE | { NO CYCLE } ]
    [ { CACHE [  <constant> ] } | { NO CACHE } ]
    [ ; ]

You start with the CREATE SEQUENCE expression.

Characteristics of a Sequence

A sequence shares many characteristics with an identity column but adds some others. Therefore, the characteristics of a sequence are:

Using a Sequence

After creating a sequence, it becomes an object you can use in any new table. Because a sequence generates (unique increment/decrement) values that a column would use, when creating the field on a table, specify its data type as the same or compatible type that the sequence is using. Here is an example:

CREATE TABLE Inventory.StoreItems
(
    ItemNumber int,
    ItemName nvarchar(60),
    UnitPrice money
);
GO

A sequence is used during data entry. When specifying the value of its column, type a formula as:

NEXT VALUE FOR [schema_name . ] sequence_name

The database engine would then find the next number in the sequence and assign it to the column. Here are examples:

using System;
using System.Data;
using System.Drawing;
using System.Windows.Forms;
using System.Data.SqlClient;

public class Exercise : System.Windows.Forms.Form
{
    Button btnCreateObjects;
    Button btnAddStoreItems;
    Button btnShowRecords;
    DataGridView dgvStoreItems;
    
    public Exercise()
    {
        InitializeComponent();
    }

    void InitializeComponent()
    {
        btnCreateObjects = new Button();
        btnCreateObjects.Text = "Create Objects";
        btnCreateObjects.Width = 100;
        btnCreateObjects.Location = new Point(12, 12);
        btnCreateObjects.Click += new EventHandler(btnCreateTableClick);

        btnAddStoreItems = new Button();
        btnAddStoreItems.Text = "Add Store Items";
        btnAddStoreItems.Location = new Point(120, 12);
        btnAddStoreItems.Width = 100;
        btnAddStoreItems.Click += new EventHandler(btnAddStoreItemsClick);

        btnShowRecords = new Button();
        btnShowRecords.Text = "Show Store Items";
        btnShowRecords.Width = 100;
        btnShowRecords.Location = new Point(230, 12);
        btnShowRecords.Click += new EventHandler(btnShowRecordsClick);

        dgvStoreItems = new DataGridView();
        dgvStoreItems.Location = new Point(12, 46);

        Text = "Exercise";
        Controls.Add(btnCreateObjects);
        Controls.Add(btnAddStoreItems);
        Controls.Add(btnShowRecords);
        Controls.Add(dgvStoreItems);

        StartPosition = FormStartPosition.CenterScreen;
        dgvStoreItems.Width = this.Width - 30;
        dgvStoreItems.Height = this.Height - 80;
        dgvStoreItems.Anchor = AnchorStyles.Left | AnchorStyles.Top |
                             AnchorStyles.Right | AnchorStyles.Bottom;
    }

    private void btnCreateTableClick(object sender, EventArgs e)
    {
        using (SqlConnection cntExercise =
            new SqlConnection("Data Source=(local);" +
                              "Database='Exercise1';" +
                              "Integrated Security=yes;"))
        {
            SqlCommand cmdStoreItems =
                new SqlCommand("CREATE SCHEMA Inventory;",
                               cntExercise);
            cntExercise.Open();
            cmdStoreItems.ExecuteNonQuery();
        }

        using (SqlConnection cntExercise =
            new SqlConnection("Data Source=(local);" +
                              "Database='Exercise1';" +
                              "Integrated Security=yes;"))
        {
            SqlCommand cmdStoreItems =
                new SqlCommand("CREATE TABLE Inventory.StoreItems" +
                               "(" +
                               "    ItemNumber int," +
                               "    ItemName nvarchar(60)," +
                               "    UnitPrice money" +
                               ");",
                               cntExercise);
            cntExercise.Open();
            cmdStoreItems.ExecuteNonQuery();
        }

        using (SqlConnection cntExercise =
            new SqlConnection("Data Source=(local);" +
                              "Database='Exercise1';" +
                              "Integrated Security=yes;"))
        {
            SqlCommand cmdStoreItems =
                new SqlCommand("CREATE SEQUENCE Inventory.ItemsCodes " +
                               "AS int " +
                               "START WITH 10001 " +
                               "INCREMENT BY 1;",
                               cntExercise);
            cntExercise.Open();
            cmdStoreItems.ExecuteNonQuery();
        }
    }

    private void btnAddStoreItemsClick(object sender, EventArgs e)
    {
        using (SqlConnection cntExercise =
            new SqlConnection("Data Source=(local);" +
                              "Database='Exercise1';" +
                              "Integrated Security=yes;"))
        {
            SqlCommand cmdStoreItems =
                new SqlCommand("INSERT INTO Inventory.StoreItems " +
                               "VALUES(NEXT VALUE FOR Inventory.ItemsCodes, N'Short Sleeve Shirt', 34.95)," +
                               "      (NEXT VALUE FOR Inventory.ItemsCodes, N'Tweed Jacket', 155.00)," +
                               "      (NEXT VALUE FOR Inventory.ItemsCodes, N'Evaded Mini-Skirt', 72.45)," +
                               "      (NEXT VALUE FOR Inventory.ItemsCodes, N'Lombardi Men''s Shoes', 79.95);",
                               cntExercise);
            cntExercise.Open();
            cmdStoreItems.ExecuteNonQuery();
        }
    }

    private void btnShowRecordsClick(object sender, EventArgs e)
    {
        using (SqlConnection cntExercise =
            new SqlConnection("Data Source=(local);" +
                              "Database='Exercise1';" +
                              "Integrated Security=yes;"))
        {
            SqlCommand cmdStoreItems =
                new SqlCommand("SELECT ALL * FROM Inventory.StoreItems;",
                               cntExercise);
            cntExercise.Open();
            cmdStoreItems.ExecuteNonQuery();

            SqlDataAdapter sdaStoreItems = new SqlDataAdapter(cmdStoreItems);
            BindingSource bsStoreItems = new BindingSource();

            DataSet dsStoreItems = new DataSet("StoreItemsSet");
            sdaStoreItems.Fill(dsStoreItems);

            bsStoreItems.DataSource = dsStoreItems.Tables[0];
            dgvStoreItems.DataSource = bsStoreItems;
        }
    }
}

public class Program
{
    [STAThread]
    static int Main()
    {
        System.Windows.Forms.Application.Run(new Exercise());
        return 0;
    }
}

Using a Sequence

Details on Sequences

Sharing a Sequence

A sequence can be shared by many tables. This means that, after creating a sequence, you can apply it on any table that needs that series of numbers. When using a sequence from one table to another, if you use the NEXT VALUE FOR routine, the series would continue from where it left up. This is not an anomaly. It is by design, so that various tables can share the same sequence.

Resetting a Sequence

Resetting a sequence consists of restarting it from a certain point. To do this, use the following formula:

ALTER SEQUENCE [schema_name. ] sequence_name
    [ RESTART [ WITH constant ] ]
    [ INCREMENT BY constant ]
    [ { MINVALUE constant } | { NO MINVALUE } ]
    [ { MAXVALUE constant } | { NO MAXVALUE } ]
    [ CYCLE | { NO CYCLE } ]
    [ { CACHE [ constant ] } | { NO CACHE } ]
    [ ; ]

Setting a Sequence as Default

So far, to specify the value of a column with sequence, we were calling NEXT VALUE FOR. If you know that you will keep caling a sequence to provide the values of a column, you can set that sequence as the default value of the column. If you do this, you can omit the column in the INSERT statement. Here is an example:

USE LambdaSquare1;
GO
CREATE TABLE Rentals.Registrations
(
	RegistrationID int not null
		DEFAULT (NEXT VALUE FOR Rentals.SeqRegistrations),
	RegistrationDate Date,
	EmployeeNumber int, -- Processed By
	TenantCode int, -- Processed For
	UnitNumber int not null,
	RentStartDate date,
	Notes nvarchar(max)
);
GO

After doing this, you can create the values of the column as done for an identity, by omiting the name of the column in the INSERT statement.

INSERT INTO Academics.UndergraduateStudents(StudentNumber, FirstName, MiddleName, LastName, BirthDate, Gender, EmailAddress, MajorID, MinorID, Username)
VALUES(N'88130480', N'Marie', N'Annette', N'Robinson', Administration.SetDateOfBirth(-6817), N'F', N'mrobinson@yahoo.com',    1021, 1004, N'mrobinson'),
      (N'24795711', N'Roger', N'Dermot',  N'Baker',    Administration.SetDateOfBirth(-6570), N'M', N'rbaker2020@hotmail.com', 1005, 1002, N'rbaker');
GO
INSERT INTO Academics.UndergraduateStudents(StudentNumber, FirstName, LastName, BirthDate, Gender, EmailAddress, MajorID, MinorID, Username)
VALUES(N'18073572', N'Patrick', N'Wisne', Administration.SetDateOfBirth(-11012), N'M', N'pwisdom@attmail.com', 1001, 1008, N'pwisne');
GO
 

Previous Copyright © 2014-2022, FunctionX Home