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.

Practical LearningPractical Learning: Introducing Sequances

  1. Start Microsoft SQL Server connect
  2. Right-click the name of the server and click New Query

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...

Visually Creating a Sequence

This would present the New Sequence dialog box with some default (basic) values:

New Sequence

We will review all the options of this dialog box in the next sections.

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:

Practical LearningPractical Learning: Creating Sequences

  1. In the Object Explorer, under University6 (the University6 database was created in the previous lesson), expand Programmability
  2. Right-click Sequences and click New Sequence...
  3. In the Sequence Name, type SeqSchedules
  4. On the right side of the Sequence Schema text box, click the browse button Ellipsis
  5. In the Enter the Object Names text box, type Academics
  6. Click Check Names and notice that [Academics] has been selected
  7. Click OK
  8. In the Data Type combo box, select int
  9. In the Start Value text box, type 10101
  10. In the Increment By text box, type 1
     
    New Sequence
  11. Click OK
  12. Click inside the Query Editor and press Ctrl + A
  13. To programmatically create a sequence and a table that would use it, type the following code:
    USE University6;
    GO
    
    CREATE SEQUENCE Academics.SeqStudents
        AS Int
        START WITH   1
        INCREMENT BY 1;
    GO
  14. To execute, press F5

Using a Sequence

After creating a sequence, it becomes an object you can use in any new table. Because a sequence generates (unique incremental) 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:

CREATE SCHEMA Inventory;
GO
CREATE SEQUENCE Inventory.ItemsCodes
    AS int
	START WITH 10001
	INCREMENT BY 1;
GO
CREATE TABLE Inventory.StoreItems
(
	ItemNumber int,
	ItemName nvarchar(60),
	UnitPrice money
);
GO
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);
GO

This would produce:

ItemNumber ItemName UnitPrice
10001 Short Sleeve Shirt 34.95
10002 Tweed Jacket 155.00
10003 Evaded Mini-Skirt 72.45
10004 Lombardi Men's Shoes 79.95
 

Practical LearningPractical Learning: Using Sequences

  1. Click inside the Query Editor and press Ctrl + A
  2. Type the following:
    USE University6;
    GO
    
    INSERT INTO Academics.UndergraduateSchedules(UndergraduateScheduleID, SemesterID, StartDate, EndDate, TeacherNumber, CourseCode, CourseDeliveryTypeCode, LocationCode)
    VALUES(NEXT VALUE FOR Academics.SeqSchedules, 101, N'20120109', N'20120205', N'820384', N'LBRS 100', N'L', N'ONLNE'),
          (NEXT VALUE FOR Academics.SeqSchedules, 101, N'20120109', N'20120205', N'979384', N'LBRS 100', N'L', N'ONLNE');
    GO
    INSERT INTO Academics.UndergraduateSchedules(UndergraduateScheduleID, SemesterID, StartDate, EndDate, StartTime, EndTime, Weekdays, TeacherNumber, CourseCode, CourseDeliveryTypeCode, LocationCode, RoomNumber)
    VALUES(NEXT VALUE FOR Academics.SeqSchedules, 101, N'20120109', N'20120318', N'08:15', N'10:10', N'M-W', N'293804', N'WRTG 101', N'F', N'LATAC', N'204'),
          (NEXT VALUE FOR Academics.SeqSchedules, 101, N'20120109', N'20120318', N'10:25', N'12:20', N'M-W', N'293804', N'WRTG 101', N'F', N'LATAC', N'104'),
          (NEXT VALUE FOR Academics.SeqSchedules, 101, N'20120109', N'20120226', N'08:15', N'10:10', N'M-W-F', N'293804', N'WRTG 101', N'F', N'LATAC', N'102'),
          (NEXT VALUE FOR Academics.SeqSchedules, 101, N'20120109', N'20120226', N'10:25', N'12:20', N'M-W-F', N'293804', N'WRTG 101', N'F', N'LATAC', N'102'),
          (NEXT VALUE FOR Academics.SeqSchedules, 101, N'20120109', N'20120318', N'10:25', N'12:20', N'M-W', N'520203', N'MATH 106', N'F', N'LATAC', N'102');
    GO
  3. To execute, press F5
  4. Click inside the Query Editor and press Ctrl + A
  5. To see a list of schedules, type the following code:
    SELECT schd.*
    FROM Academics.UndergraduateSchedules schd;
    GO
  6. To execute the statement, press F5

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 } ]
    [ ; ]

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.

Practical LearningPractical Learning: Resetting a Sequence

  1. Click inside the Query Editor and press Ctrl + A
  2. Type the following:
    USE University6;
    GO
    
    ALTER SEQUENCE Academics.SeqSchedules
    RESTART WITH 10201
    INCREMENT BY 1;
    GO
    
    INSERT INTO Academics.UndergraduateSchedules(UndergraduateScheduleID, SemesterID, StartDate, EndDate, StartTime, EndTime, Weekdays, TeacherNumber, CourseCode, CourseDeliveryTypeCode, LocationCode, RoomNumber)
    VALUES(NEXT VALUE FOR Academics.SeqSchedules, 102, N'20120514', N'20120819', N'08:15', N'10:10', N'M-W', N'293804', N'WRTG 101', N'F', N'LATAC', N'204');
    GO
    INSERT INTO Academics.UndergraduateSchedules(UndergraduateScheduleID, SemesterID, StartDate, EndDate, StartTime, EndTime, Weekdays, TeacherNumber, CourseCode, CourseDeliveryTypeCode, LocationCode, RoomNumber)
    VALUES(NEXT VALUE FOR Academics.SeqSchedules, 102, N'20120514', N'20120819', N'10:25', N'12:20', N'M-W', N'603925', N'EDPD 100', N'F', N'HMNSS', N'101');
    GO
    INSERT INTO Academics.UndergraduateSchedules(UndergraduateScheduleID, SemesterID, StartDate, EndDate, StartTime, EndTime, Weekdays, TeacherNumber, CourseCode, CourseDeliveryTypeCode, LocationCode, RoomNumber)
    VALUES(NEXT VALUE FOR Academics.SeqSchedules, 102, N'20120514', N'20120819', N'08:15', N'10:10', N'T-H', N'520203', N'MATH 106', N'F', N'LATAC', N'104');
    GO
    INSERT INTO Academics.UndergraduateSchedules(UndergraduateScheduleID, SemesterID, StartDate, EndDate, TeacherNumber, CourseCode, CourseDeliveryTypeCode, LocationCode)
    VALUES(NEXT VALUE FOR Academics.SeqSchedules, 102, N'20120514', N'20120205', N'820384', N'LBRS 100', N'L', N'ONLNE');
    GO
    INSERT INTO Academics.UndergraduateSchedules(UndergraduateScheduleID, SemesterID, StartDate, EndDate, StartTime, EndTime, Weekdays, TeacherNumber, CourseCode, CourseDeliveryTypeCode, LocationCode, RoomNumber)
    VALUES(NEXT VALUE FOR Academics.SeqSchedules, 102, N'20120514', N'20120819', N'08:15', N'10:10', N'M-W', N'160205', N'CMSC 101', N'F', N'SEAMT', N'210');
    GO
    INSERT INTO Academics.UndergraduateSchedules(UndergraduateScheduleID, SemesterID, StartDate, EndDate, StartTime, EndTime, Weekdays, TeacherNumber, CourseCode, CourseDeliveryTypeCode, LocationCode, RoomNumber)
    VALUES(NEXT VALUE FOR Academics.SeqSchedules, 102, N'20120514', N'20120819', N'13:25', N'15:20', N'M-W', N'297940', N'MATH 115', N'F', N'NAASB', N'102');
    GO
    INSERT INTO Academics.UndergraduateSchedules(UndergraduateScheduleID, SemesterID, StartDate, EndDate, StartTime, EndTime, Weekdays, TeacherNumber, CourseCode, CourseDeliveryTypeCode, LocationCode, RoomNumber)
    VALUES(NEXT VALUE FOR Academics.SeqSchedules, 102, N'20120514', N'20120819', N'08:15', N'10:10', N'T-H', N'283029', N'HIST 140', N'F', N'HMNSS', N'103');
    GO
    
    ALTER SEQUENCE Academics.SeqSchedules
    RESTART WITH 10301
    INCREMENT BY 1;
    GO
    
    INSERT INTO Academics.UndergraduateSchedules(UndergraduateScheduleID, SemesterID, StartDate, EndDate, StartTime, EndTime, Weekdays, TeacherNumber, CourseCode, CourseDeliveryTypeCode, LocationCode, RoomNumber)
    VALUES(NEXT VALUE FOR Academics.SeqSchedules, 103, N'20120920', N'20121014', N'08:15', N'10:10', N'M-W', N'293804', N'WRTG 101', N'F', N'LATAC', N'101');
    GO
    INSERT INTO Academics.UndergraduateSchedules(UndergraduateScheduleID, SemesterID, StartDate, EndDate, StartTime, EndTime, Weekdays, TeacherNumber, CourseCode, CourseDeliveryTypeCode, LocationCode, RoomNumber)
    VALUES(NEXT VALUE FOR Academics.SeqSchedules, 103, N'20120920', N'20121014', N'10:25', N'12:20', N'M-W', N'640840', N'MATH 106', N'F', N'LATAC', N'106');
    GO
    INSERT INTO Academics.UndergraduateSchedules(UndergraduateScheduleID, SemesterID, StartDate, EndDate, StartTime, EndTime, Weekdays, TeacherNumber, CourseCode, CourseDeliveryTypeCode, LocationCode, RoomNumber)
    VALUES(NEXT VALUE FOR Academics.SeqSchedules, 103, N'20120920', N'20121014', N'13:25', N'15:20', N'M-W', N'283029', N'HIST 140', N'F', N'HMNSS', N'103');
    GO
    INSERT INTO Academics.UndergraduateSchedules(UndergraduateScheduleID, SemesterID, StartDate, EndDate, StartTime, EndTime, Weekdays, TeacherNumber, CourseCode, CourseDeliveryTypeCode, LocationCode, RoomNumber)
    VALUES(NEXT VALUE FOR Academics.SeqSchedules, 103, N'20120920', N'20121014', N'13:25', N'15:20', N'T-H', N'283029', N'HIST 140', N'F', N'HMNSS', N'103');
    GO
    
    ALTER SEQUENCE Academics.SeqSchedules
    RESTART WITH 10401
    INCREMENT BY 1;
    GO
    
    INSERT INTO Academics.UndergraduateSchedules(UndergraduateScheduleID, SemesterID, StartDate, EndDate, StartTime, EndTime, Weekdays, TeacherNumber, CourseCode, CourseDeliveryTypeCode, LocationCode, RoomNumber)
    VALUES(NEXT VALUE FOR Academics.SeqSchedules, 104, N'20130107', N'20130217', N'08:15', N'10:10', N'M-W', N'283029', N'HIST 140', N'F', N'HMNSS', N'105');
    GO
    INSERT INTO Academics.UndergraduateSchedules(UndergraduateScheduleID, SemesterID, StartDate, EndDate, StartTime, EndTime, Weekdays, TeacherNumber, CourseCode, CourseDeliveryTypeCode, LocationCode, RoomNumber)
    VALUES(NEXT VALUE FOR Academics.SeqSchedules, 104, N'20130107', N'20130217', N'15:35', N'17:30', N'M-W', N'249382', N'GVPS 140', N'F', N'HMNSS', N'107');
    GO
    
    
  3. To execute, press F5
  4. Click inside the Query Editor and press Ctrl + A
  5. To see a list of schedules, type the following code:
    SELECT schd.UndergraduateScheduleID,
           schd.SemesterID, 
           schd.StartDate, 
           schd.EndDate, 
           schd.TeacherNumber, 
           schd.CourseCode, 
           schd.CourseDeliveryTypeCode, 
           schd.LocationCode
    FROM Academics.UndergraduateSchedules schd;
    GO
  6. To execute the statement, press F5

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

Practical LearningPractical Learning: Setting a Sequence as Default

  1. Click inside the the Query Editor and press Ctrl + A
  2. Type the following:
    USE University6;
    GO
    
    CREATE TABLE Academics.UndergraduateStudents
    (
        StudentID int not null
    	DEFAULT (NEXT VALUE FOR Academics.SeqStudents),
        StudentNumber nvarchar(8) not null,
        FirstName nvarchar(20),
        MiddleName nvarchar(20),
        LastName nvarchar(20),
        BirthDate date,
        Gender nvarchar(3) default N'N/A',
        MajorID int not null
    );
    GO
    
    INSERT INTO Academics.UndergraduateStudents(StudentNumber, FirstName, MiddleName, LastName, BirthDate, Gender, MajorID)
    VALUES(N'88130480', N'Marie', N'Annette', N'Robinson', Administration.SetDateOfBirth(-6817), N'F', 1021),
          (N'24795711', N'Roger', N'Dermot',  N'Baker',    Administration.SetDateOfBirth(-6570), N'M', 1005);
    GO
    INSERT INTO Academics.UndergraduateStudents(StudentNumber, FirstName, LastName, BirthDate, Gender, MajorID)
    VALUES(N'18073572', N'Patrick', N'Wisne', Administration.SetDateOfBirth(-11012), N'M', 1001);
    GO
    INSERT INTO Academics.UndergraduateStudents(StudentNumber, FirstName, MiddleName, LastName, BirthDate, Gender, MajorID)
    VALUES(N'22803048', N'Gary', N'Jonathan', N'Jones', Administration.SetDateOfBirth(-19926), N'M', 1019),
          (N'97394285', N'Jessica', N'Danielle', N'Weisburgh', Administration.SetDateOfBirth(-12081), N'F', 1009),
          (N'97596002', N'Laurent', N'Frank', N'Simonson', Administration.SetDateOfBirth(-17503), N'M', 1016),
          (N'94708257', N'Christopher', N'Sheldon', N'Dale', Administration.SetDateOfBirth(-6570),  N'M', 1006),
          (N'48009520', N'Diane', N'Kathy', N'Paglia', Administration.SetDateOfBirth(-13840), N'F', 1006),
          (N'13048039', N'Joseph', N'Christian', N'Riback', Administration.SetDateOfBirth(-7909),  N'M', 1011),
          (N'92270397', N'Patrick', N'Jonathan', N'Brzeniak', Administration.SetDateOfBirth(-17361), N'M', 1021);
    GO
    INSERT INTO Academics.UndergraduateStudents(StudentNumber, FirstName, LastName, BirthDate, Gender, MajorID)
    VALUES(N'70840584', N'Tracy', N'Sikorowski', Administration.SetDateOfBirth(-11650), N'M', 1006);
    GO
    
    
  3. Right-click anywhere in the window and click Execute
  4. Click inside the Query Editor and press Ctrl + A
  5. To see a list of students, type the following:
    SELECT Students.StudentID ID,
           Students.StudentNumber [Student #],
           Students.FirstName [First Name],
           Students.MiddleName [Middle Name],
           Students.LastName [Last Name],
           FORMAT(Students.BirthDate, N'D') [Birth Date],
           DATEDIFF(yyyy, BirthDate, SYSDATETIME()) Age,
           CASE Students.Gender
    		WHEN N'M' THEN N'Male'
    		WHEN N'F' THEN N'Female'
    		ELSE N'Unknown'
           END Gender,
           MajorID Major
    FROM Academics.UndergraduateStudents Students
    ORDER BY Students.StudentID;
    GO
  6. To execute, press F5
  7. Close Microsoft SQL Server
  8. If asked whether you want to save the file, click No

Previous Copyright © 2012-2022, FunctionX Next