【SQL】 Create Table With Prefix Running Number
>
>
【SQL】 Create Table With Prefix Running Number

SQL - Create Table With Prefix Running Number

SQL - Create Table With Prefix Running Number

In this post, we will explore how to create a table in SQL Server that includes a prefix and a running number. This can be useful in scenarios where you need to generate unique identifiers for your data that include a specific prefix followed by a sequential number.

Table of - contents

No.
Title
1
Table With Running Number (SQL Server)
2
Table With Fixed Prefix + Running Number
3
Table Use Input As Prefix + Running Number
4
Table Use Input As Prefix + Counter Reset Counter When Different Prefix

1 - Table With Running Number (SQL Server).

CREATE TABLE [dbo].[Customer](
    [RunningNo] [bigint] IDENTITY(10000,1) NOT NULL,
    [UserInput1] [varchar](50) NULL,
    [UserInput2] [varchar](50) NULL,
    CONSTRAINT [PK_Customer] PRIMARY KEY NONCLUSTERED 
    (
        [RunningNo] ASC
    )WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]
a) CREATE TABLE [dbo].[Customer](: This line starts the creation of a new table named “Customer” in the “dbo” schema. The table definition is enclosed in parentheses.

b) [RunningNo] [bigint] IDENTITY(10000,1) NOT NULL,: This line defines a column named “RunningNo” of data type “bigint.” The “IDENTITY(10000,1)” indicates that the values in this column will be automatically generated in an incremental manner, starting from 10000 with a step of 1. The “NOT NULL” constraint ensures that this column cannot have a null value.

c) [UserInput1] [varchar](50) NULL,: This line defines a column named “UserInput1 and UserInput2” of data type “varchar(50).” The “varchar(50)” specifies that this column can store variable-length character data up to a maximum of 50 characters. The “NULL” keyword indicates that this column can have null values.
d) CONSTRAINT [PK_Customer] PRIMARY KEY NONCLUSTERED: This line introduces a primary key constraint on the table. The constraint is named “PK_Customer,” and it ensures that the “RunningNo” column is unique and serves as the primary key for this table.
e) ([RunningNo] ASC): This line specifies that the “RunningNo” column is used as the primary key, and the “ASC” keyword indicates that the values should be sorted in ascending order.
f) WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON): This line provides additional options for index creation. Here, various options are set to control index behavior such as padding, statistics recalculation, duplicate key handling, and locking.
g) ON [PRIMARY]: This line specifies that the table will be created on the “PRIMARY” filegroup.
Output:
RunningNo  |  UserInput1  |  UserInput2
--------------------------------------
10000      |  Value1      |  Value2
10001      |  Value3      |  Value4
In summary, this script creates a table named “Customer” with three columns: “RunningNo,” “UserInput1,” and “UserInput2.” The “RunningNo” column is defined as an automatically generated primary key, while the other two columns can store user input of up to 50 characters.

2 - Table With Fixed Prefix + Running Number

CREATE TABLE [dbo].[Customer](
    [RunningNo] [bigint] IDENTITY(10000,1) NOT NULL,
    [ID] AS ('CUST-' + CAST([RunningNo] AS varchar(20))) PERSISTED,
	[UserInput1] [varchar](50) NULL,
    [UserInput2] [varchar](50) NULL,
    
    CONSTRAINT [PK_Customer] PRIMARY KEY NONCLUSTERED 
    (
        [RunningNo] ASC
    )WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]
a) [ID] AS (‘CUST-‘ + CAST([RunningNo] AS varchar(20))) PERSISTED: This line defines a computed column named “ID”. The value of this column is generated based on the value of the “RunningNo” column. It concatenates the string “CUST-” with the converted value of “RunningNo” using CAST function. The resulting value is stored in the column. The PERSISTED keyword indicates that the computed value will be physically stored in the table and not calculated dynamically.
Output:
RunningNo  |    ID         |  UserInput1   |  UserInput2
------------------------------------------------------
10000      | CUST-10000    |  Value1       |  Value2
10001      | CUST-10001    |  Value3       |  Value4

3 - Table Use Input As Prefix + Running Number.

CREATE TABLE [dbo].[Customer](
    [RunningNo] [bigint] IDENTITY(10000,1) NOT NULL,
    [ID] AS ([UserInput1] + '-' + CAST([RunningNo] AS varchar(20))) PERSISTED,
    [UserInput1] [varchar](50) NULL,
    [UserInput2] [varchar](50) NULL,
    CONSTRAINT [PK_Customer] PRIMARY KEY NONCLUSTERED 
    (
        [RunningNo] ASC
    )WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]RunningNo	ID	UserInput1	UserInput2
10000	John-10000	John	Doe
10001	Jane-10001	Jane	Smith
a) [ID] AS ([UserInput1] + ‘-‘ + CAST([RunningNo] AS varchar(20))) PERSISTED: This line defines a computed column named “ID”. The value of this column is derived from concatenating the value of the “UserInput1” column with a hyphen “-” and the converted value of the “RunningNo” column. The “PERSISTED” keyword indicates that the computed column is physically stored in the table.
Output:
RunningNo  |    ID         |  UserInput1   |  UserInput2
------------------------------------------------------
10000      | John-10000    |  John       |  Value1
10001      | Jane-10001    |  Jane       |  Value2
  • The “RunningNo” column is an automatically generated identity column starting from 10,000, so it increments by 1 for each new record inserted.
  • The “ID” column is a computed column that concatenates the value from the “UserInput1” column with a hyphen and the value from the “RunningNo” column. In this case, it combines the values to create a unique identifier for each record.
  • The “UserInput1” and “UserInput2” columns store the values provided during record insertion.
  • The primary key constraint “PK_Customer” ensures that the “RunningNo” column is unique and serves as the primary key for the table.

4 - Table Use Input As Prefix + Counter Reset Counter When Different Prefix.

CREATE TABLE [dbo].[Customer](
    [RunningNo] [bigint] IDENTITY(10000,1) NOT NULL,
	[Counter] [bigint] NOT NULL DEFAULT 10000,
    [ID] [varchar](70) NULL,
	[UserInput1] [varchar](50) NULL,
    [UserInput2] [varchar](50) NULL,  
	
    CONSTRAINT [PK_Customer] PRIMARY KEY NONCLUSTERED 
    (
        [RunningNo] ASC
    )WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]
CREATE TRIGGER [dbo].[Trigger_Customer]
ON [dbo].[Customer]
AFTER INSERT
AS
BEGIN
    SET NOCOUNT ON;

    DECLARE @UserInput1 VARCHAR(50);
    DECLARE @Counter BIGINT;

    SELECT @UserInput1 = UserInput1 FROM inserted;

    -- Check if the combination of UserInput1 already exists
    IF EXISTS (
        SELECT 1
        FROM [dbo].[Customer]
        WHERE UserInput1 = @UserInput1
    )
    BEGIN
        -- Retrieve the current maximum Counter value for the combination
        SELECT @Counter = MAX([Counter])
        FROM [dbo].[Customer]
        WHERE UserInput1 = @UserInput1;
    END
    ELSE
    BEGIN
        -- Combination does not exist, start Counter from the beginning
        SET @Counter = 100000;
    END

    -- Increment the Counter for the combination
    UPDATE [dbo].[Customer]
    SET [Counter] = @Counter +1
    WHERE UserInput1 = @UserInput1 AND [RunningNo] IN (SELECT [RunningNo] FROM inserted);

    -- Update the inserted rows with the concatenated ID
    UPDATE rh
    SET ID = CONCAT(@UserInput1, '-', rh.[Counter])
    FROM [dbo].[Customer] rh
    INNER JOIN inserted i ON rh.RunningNo = i.RunningNo;
END
a) [Counter] [bigint] NOT NULL DEFAULT 10000,: This line defines a column named “Counter” of type “bigint” (a large integer) that stores a counter value. The column is marked as “NOT NULL” and has a default value of 10000.
b) CREATE TRIGGER [dbo].[Trigger_Customer] ON [dbo].[Customer] AFTER INSERT AS: This line creates a trigger named “Trigger_Customer” on the “Customer” table. The trigger will fire after an insert operation on the table.
c) SET NOCOUNT ON;: This line instructs SQL Server to suppress the message indicating the number of rows affected by the trigger.
Output:
RunningNo  |  Counter  |    ID         |  UserInput1   |  UserInput2
------------------------------------------------------
10000  |   10001   | CUST-10001    |  CUST       |  Value1
10001  |   10002   | CUST-10002    |  CUST       |  Value2
10002  |   10003   | CUST-10003    |  CUST       |  Value1
10003  |   10001   | VEND-10001   |  VEND     |  Value2
10004  |   10002   | VEND-10002   |  VEND     |  Value2
The Counter column is incremented for each unique value in the UserInput1 column, starting from 10000. The ID column is updated by concatenating the UserInput1 value with the corresponding Counter value.
Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments

Search

.
Xiao. tian
.

Piano - Music

.

Recent - Post

.
0 0 votes
Article Rating

Start typing and press Enter to search

Shopping Cart
0
Would love your thoughts, please comment.x
()
x