0

我有以下表定义:

        CREATE TABLE Content (
            [ContentId] INT IDENTITY (1, 1) NOT NULL,
            [Title] NVARCHAR (50) Not NULL,
            CONSTRAINT [PK_Content] PRIMARY KEY CLUSTERED ([ContentId] ASC)
        )";

而不是标识列,我需要为 ContentId 生成一个随机的 5 位数字,并且该数字以前没有被使用过

有没有办法通过某种数据库触发器在 SQL Server 2012 中进行插入来做到这一点?

4

2 回答 2

2

您只处理 100,000 个值。我的建议是创建一个查找表,用于将自动递增的 id 映射到新的 id。下面是创建这样一个表的代码:

with nums as (
      select 0 as n
      union all
      select n + 1
      from nums
      where n < 9
     ),
     nums5 as (
      select n1.n*10000+n2.n*1000+n3.n*100+n4.n+10+n5.n as val
      from nums n1 cross join nums n2 cross join nums n3 cross join
           nums n4 cross join nums n5
    )
select val,
       row_number() over (order by newid()) as new_content_id
into LookupTable
from nums5;

使用此表,将自动递增的 id 放入表中,然后从该表中查找五个字符“new_content_id”。

于 2013-09-01T20:17:18.153 回答
1

这可能是做你想做的事情的一个很好的起点:

SQL小提琴

MS SQL Server 2012 架构设置

CREATE TABLE Content (
            [ContentId] INT NOT NULL,
            [Title] NVARCHAR (50) Not NULL,
            CONSTRAINT [PK_Content] PRIMARY KEY CLUSTERED ([ContentId] ASC)
        );

查询 1

DECLARE @key VARCHAR(5), @i int
DECLARE @query VARCHAR(120)
SET @i = 1
WHILE @i > 0
BEGIN
    SET @key = (SELECT ABS(Checksum(NewID()) % 89999) + 10000)
    SET @i = (SELECT count(*) FROM Content WHERE ContentId = @key)
END
SET @query = 'INSERT INTO Content (ContentId,Title) VALUES ('+@key+',''Whatever'+@key+''');'
exec(@query)

结果

查询 2

DECLARE @key VARCHAR(5), @i int
DECLARE @query VARCHAR(120)
SET @i = 1
WHILE @i > 0
BEGIN
    SET @key = (SELECT ABS(Checksum(NewID()) % 89999) + 10000)
    SET @i = (SELECT count(*) FROM Content WHERE ContentId = @key)
END
SET @query = 'INSERT INTO Content (ContentId,Title) VALUES ('+@key+',''Whatever'+@key+''');'
exec(@query)

结果

查询 3

select * from Content

结果

| CONTENTID |         TITLE |
|-----------|---------------|
|     22537 | Whatever22537 |
|     66089 | Whatever66089 |
于 2013-09-01T20:09:48.887 回答