自动生成不一致的唯一密钥

时间:2018-11-18 04:32:18

标签: sql sql-server tsql

我正在尝试以以下格式创建唯一键:

ABC123456

因此,例如,它将以ABC000001开始并以ABC999999结尾,基本上前三个字符是ABC,然后是6个数字。

我目前有以下查询:

  SELECT 
    'ABC' + CAST(REPLICATE('0',6-LEN(RTRIM(ROW_NUMBER() OVER (ORDER BY (SELECT NULL))))+ (SELECT Counter from Counters)) + RTRIM(ROW_NUMBER() OVER (ORDER BY (SELECT NULL)) + (SELECT Counter from Counters)) as CHAR(9)) as InvoiceNumber,
    ID,
    RandomNumber
 from
    RandomNumbers

以下是一些示例数据:

CREATE TABLE [dbo].[Counters](
    [Counter] [int] NULL
) ON [PRIMARY]
INSERT INTO [dbo].[Counters]
           ([Counter])
     VALUES
           (0)

CREATE TABLE [dbo].[RandomNumbers](
    [ID] [int] NULL,
    [RandomNumber] [int] NULL
) ON [PRIMARY]
GO

with randowvalues
    as(
       select 1 id, CAST(RAND(CHECKSUM(NEWID()))*100 as int) randomnumber
        union  all
        select id + 1, CAST(RAND(CHECKSUM(NEWID()))*100 as int)  randomnumber
        from randowvalues
        where 
          id < 1000
      )

Insert into RandomNumbers
(
ID,
RandomNumber
)
select *
from randowvalues
OPTION(MAXRECURSION 0)

最初,您会看到它运行良好,但是如果运行此示例,则:

Update Counters
Set Counter = 1

,然后重新运行主查询,它将编号删除。我在这里做什么错了?

2 个答案:

答案 0 :(得分:1)

使用STUFF()函数:

with
    cte
as
(
    SELECT 
        ROW_NUMBER() OVER (ORDER BY (SELECT NULL)) + (SELECT Counter from Counters) as InvNo,
        ID,
        RandomNumber,
        'ABC000000' as SampleNo
    from
        RandomNumbers
)
select
    stuff(SampleNo, (Len(SampleNo) - Len(InvNo)) + 1, Len(SampleNo), InvNo) as InvoiceNumber,
    ID,
    RandomNumber
from
    cte;

答案 1 :(得分:1)

关于这一点,如果您在那里有IDENTITY列会更好

SELECT STUFF('ABC000000',
             10 - LEN( CAST(RN AS VARCHAR) ),
             LEN(CAST(RN AS VARCHAR)),
             CAST(RN AS VARCHAR)
       ) GenKey,
       SomeCols
FROM
(
   SELECT *,
          ROW_NUMBER() OVER(ORDER BY SomeCols) RN --Simulate IDENTITY column if you have one it would be better
   FROM YourTable 
) T;

返回:

+-----------+----------+
|  GenKey   | SomeCols |
+-----------+----------+
| ABC000001 | SomeData |
| ABC000002 | SomeData |
| ABC000003 | SomeData |
| ABC000004 | SomeData |
| ABC000005 | SomeData |
| ABC000006 | SomeData |
| ABC000007 | SomeData |
| ABC000008 | SomeData |
| ABC000009 | SomeData |
| ABC000010 | SomeData |
| …         |          |
+-----------+----------+

Demo

如果您已经有了IDENTITY列,那将更好,即使从GenKey中删除了一些行,甚至YourTable都超过{ {1}}行,这是 Demo 模拟这种情况。