我可以在插入上创建一个触发器,它将为SQL Server 2012中的键生成一个随机数吗?

时间:2013-09-01 19:37:05

标签: sql-server

我有以下表格定义:

        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中的插入,我是否可以使用某种数据库触发器来执行此操作?

2 个答案:

答案 0 :(得分: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”。

答案 1 :(得分:1)

这可以是做你想做的事情的好起点:

SQL Fiddle

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)

<强> Results

查询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)

<强> Results

查询3

select * from Content

<强> Results

| CONTENTID |         TITLE |
|-----------|---------------|
|     22537 | Whatever22537 |
|     66089 | Whatever66089 |