简体   繁体   English

MSSQL中唯一的字母数字键生成

[英]Unique alphanumeric key generation in MSSQL

I have table with char(4) field which is used as key. 我有带用作键的char(4)字段的表。 Value for that is generated (max + 1). 生成的值(最大值+1)。 But not it has reached to it's max(9999). 但是还没有达到最大值(9999)。 Cannot change the data type of the column since that is used it so many places. 无法更改列的数据类型,因为已在很多地方使用了该列。

I came up with a solution like below... 我想出了以下解决方案...

9999 -> A000...A999->B000...B999->Z999 -> ZA00->ZZZZ (zzzz will be OK for another 10 years) 9999-> A000 ... A999-> B000 ... B999-> Z999-> ZA00-> ZZZZ(zzzz可以再使用10年)

Please tell me is there an easy way to generate this other than doing substring() and string manipulation ? 请告诉我,除了执行substring()和字符串操作之外,还有一种简便的方法可以生成此代码吗?

Current Code : 当前代码:

DECLARE @cle smallint
SELECT @cle = isnull(MAX(CONVERT(smallint,RTRIM(cle))),0) from smnf
INSERT INTO smnf (sup, cle, dsc, exc, dirty) VALUES (@sup, CONVERT(char(4), @cle+1), @dsc, 0, 'A')
SELECT i INTO #t FROM (SELECT '0' i UNION ALL SELECT '1' UNION ALL SELECT '2' UNION ALL SELECT '3' UNION ALL SELECT '4' UNION ALL SELECT '5' UNION ALL SELECT '6' UNION ALL SELECT '7' UNION ALL SELECT '8' UNION ALL SELECT '9' UNION ALL SELECT 'A' UNION ALL SELECT 'B' UNION ALL SELECT 'C' UNION ALL SELECT 'D' UNION ALL SELECT 'E' UNION ALL SELECT 'F' UNION ALL SELECT 'G' UNION ALL SELECT 'H' UNION ALL SELECT 'I' UNION ALL SELECT 'J' UNION ALL SELECT 'K' UNION ALL SELECT 'L' UNION ALL SELECT 'M' UNION ALL SELECT 'N' UNION ALL SELECT 'O' UNION ALL SELECT 'P' UNION ALL SELECT 'Q' UNION ALL SELECT 'R' UNION ALL SELECT 'S' UNION ALL SELECT 'T' UNION ALL SELECT 'U' UNION ALL SELECT 'V' UNION ALL SELECT 'W' UNION ALL SELECT 'X' UNION ALL SELECT 'Y' UNION ALL SELECT 'Z') t

CREATE TABLE id_list (id char(4) PRIMARY KEY);

INSERT id_list
SELECT c1.i+c2.i+c3.i+c4.i
FROM #t c1, #t c2, #t c3, #t c4
WHERE c1.i+c2.i+c3.i+c4.i NOT LIKE '[0-9]%[A-Z]%'  --Eliminate alphas in the first 10000 to preserve existing ids.

When you need the next id: 当您需要下一个ID时:

DECLARE @curr_id char(4) = '9ZZZ'
DECLARE @next_id char(4)

SELECT TOP 1 @next_id = [id] FROM id_list WHERE [id] > @curr_id

PRINT @next_id

A000 A000

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM