生成随机的9位数字

时间:2014-01-06 10:28:30

标签: sql sql-server

我正在尝试生成一个随机的9位数字

例如0987654321请注意每个数字出现一次..

我试过这个:

select convert(numeric(10,0),rand() * 8999999999) + 10000000

它会生成,但在某些时候会重复数字。但客户需要确保9位数序列中没有数字出现两次..

这样需要输出..

1234567890
9870654321
1234098567
8976543120

3 个答案:

答案 0 :(得分:5)

您似乎正在尝试生成一个10位数字。我把它作为varchar,因为我不想在适用时压制前面的0:

declare @rnd varchar(10) = ''
;with a as
(
select 0 x
union all
select x + 1
from a where x < 9
), b as
(
select top 10 x from a
order by newid()
)
select @rnd += cast(x as char(1)) from b

select @rnd

你也可以写一个while循环:

DECLARE @rnd varchar(10) = '0123456789'
DECLARE @i int = len(@rnd)

;while @i > 1
  select @rnd = stuff(@rnd, rnd, 1, '') + substring(@rnd, rnd, 1), @i += -1  
  from (SELECT cast(rand(BINARY_CHECKSUM(newid()))*@i as int)+1 rnd) x

select @rnd

答案 1 :(得分:0)

如果要将这些值插入表中,还要检查是否重复。我会做以下事情:

<强> 1。创建一个视图以生成NewId

create view vw_getNewID as select newid() AS [NewId]

<强> 2。生成TVF

CREATE FUNCTION dbo.fn_GenerateRandomNumber()
RETURNS @r TABLE
(
RandomNumber varchar(10)
)

AS BEGIN

    ;WITH numbers as 
    (
    SELECT 0  AS [number]
    UNION ALL
    SELECT number + 1
    FROM numbers
    WHERE number  < 9
    )
    INSERT INTO @r
   SELECT stuff(
             (SELECT ''+ number FROM numbers CROSS APPLY dbo.vw_getNewID vgni order by vgni.NewId FOR XML PATH(''),TYPE

             ).value('.','VARCHAR(MAX)')
                , 1, 1, '')

    RETURN

END

第3。查询您的新TVF以插入您的表格。

INSERT INTO dbo.YourTable (RandomNumber)
SELECT grn.RandomNumber
FROM dbo.fn_GenerateRandomNumber() grn
LEFT JOIN dbo.YourTable t ON t.RandomNumber = grn.RandomNumber
WHERE t.RandomNumber IS NULL

**请注意,我已将输出转换为varchar以保留前导零。

答案 2 :(得分:-1)

Select top 10 *
from
(
select 100000000 + CONVERT(BIGINT, (9999999999-100000000+1)*RAND()) as rnd 
union
select 100000000 + CONVERT(BIGINT, (9999999999-100000000+1)*RAND()) as rnd 
union
select 100000000 + CONVERT(BIGINT, (9999999999-100000000+1)*RAND()) as rnd 
union
select 100000000 + CONVERT(BIGINT, (9999999999-100000000+1)*RAND()) as rnd
union
select 100000000 + CONVERT(BIGINT, (9999999999-100000000+1)*RAND()) as rnd
union
select 100000000 + CONVERT(BIGINT, (9999999999-100000000+1)*RAND()) as rnd
union
select 100000000 + CONVERT(BIGINT, (9999999999-100000000+1)*RAND()) as rnd
) as t