SQL Server中的字母数字序列

时间:2015-05-04 01:24:07

标签: sql-server sequence alphanumeric

我需要在SQL Server 2008中生成一个3个字符的字母数字序列,如下所示:

001,
002,
...,
999,
A01,
A02,
...,
A99,
B01,
B02,
...,
Z99

序列中的下一个项目将从存储过程生成并存储在NCHAR(3)表格列中。

3 个答案:

答案 0 :(得分:8)

要获得下一个序列,您可以添加Id之类的

WITH seq AS
(
    SELECT 
        ROW_NUMBER() OVER (ORDER BY x.alpha + y.number + z.number) AS Id,
        CONVERT(nchar(3), x.alpha + y.number + z.number) AS Result
    FROM 
        (
            VALUES 
            ('0'), ('1'), ('2'), ('3'), ('4'), ('5'), ('6'), ('7'), ('8'), ('9'),
            ('A'), ('B'), ('C'), ('D'), ('E'), ('F'), ('G'), ('H'), ('I'), ('J'), 
            ('K'), ('L'), ('M'), ('N'), ('O'), ('P'), ('Q'), ('R'), ('S'), ('T'), 
            ('U'), ('V'), ('W'), ('X'), ('Y'), ('Z')
        ) x(alpha),
        (
            VALUES 
            ('0'), ('1'), ('2'), ('3'), ('4'), ('5'), ('6'), ('7'), ('8'), ('9')
        ) y(number),
        (
            VALUES 
            ('0'), ('1'), ('2'), ('3'), ('4'), ('5'), ('6'), ('7'), ('8'), ('9')
        ) z(number)
    WHERE
       NOT (NOT x.alpha BETWEEN '1' AND '9' AND y.number = '0' AND z.number = '0')
)
-- Uncomment to see all results
--SELECT * FROM seq

SELECT Result FROM seq WHERE Id = (SELECT Id + 1 FROM seq WHERE Result = 'Z01')

结果

Z02

完整计数= 3573 = 999 +(26 * 99)

答案 1 :(得分:0)

建议的存储过程的另一种方法是使用@ user2864740建议的CROSS JOIN,并使用一个名为@pLastUsed的参数。然后SP返回序列中的下一个。注意这适用于所有版本的SQL Server。

{name:"XYZ"}

答案 2 :(得分:0)

共享一个示例以在SQL Server中生成字母数字序列号。

<强> For more reference, You can visit this article.

创建样本表:

CREATE TABLE dbo.tbl_TestVarcharSequence
(
    VarcharID VARCHAR(10)
    ,Name VARCHAR(255)
    ,CONSTRAINT pk_tbl_TestVarcharSequence_VarcharID PRIMARY KEY(VarcharID)
)
GO

创建一个样本序列对象:

CREATE SEQUENCE dbo.seq_TestVarcharSequenceNumber AS 
INT START WITH 1
INCREMENT BY 1;
GO

使用FORMAT函数创建序列约束:

ALTER TABLE dbo.tbl_TestVarcharSequence
ADD CONSTRAINT seq_tbl_TestVarcharSequence_VarcharID DEFAULT 
FORMAT((NEXT VALUE FOR dbo.seq_TestVarcharSequenceNumber),'ABC00#') 
FOR VarcharID;
GO

插入一些示例记录:

INSERT INTO dbo.tbl_TestVarcharSequence (Name) 
VALUES ('Anvesh'),('Alex'),('Roy'),('Bony')
GO

结果:

SELECT * FROM dbo.tbl_TestVarcharSequence

ABC001     Anvesh
ABC002     Alex
ABC003     Roy
ABC004     Bony