分类: Mysql/postgreSQL
2014-01-14 18:22:22
以下是产生1000个10位的随机数的代码方法一:
alter PROC proc_randCardID_LYJ2
AS
declare @i int
DECLARE @randCardID char(19)
DECLARE @r numeric(15,8)
set @i=1
while @i<=1000
begin
SELECT @r=RAND(
(DATEPART(mm,GETDATE())*100000)+
(DATEPART(ss,GETDATE())*1000)+
DATEPART(ms,GETDATE())
)
SET @randCardID=SUBSTRING(convert(varchar(15),@r),3,5)+SUBSTRING(convert(varchar(15),@r),5,5)
if not exists(select * from rand_CardID where CardID=@randCardID)
begin
insert rand_CardID select @randCardID
set @i=@i+1
end
end
方法二:
create procedure randCardID_xcq
as
begin
declare @i int
declare @n bigint
set @i=1
while @i<=10000
begin
set @n=(SELECT CAST(CEILING(RAND() * 10000000000) AS bigint))
if @n<1000000000 or exists(select num from #tmp where num=@n)
continue
else
begin
insert into #tmp values(@n)
set @i=@i+1
end
end
end
GO
假设五位的随机代码select cast(10000+90000*rand() as int)也可以这样产生
方法三:
drop table #t
create table #t(aa varchar(10))
----------
declare @i int
declare @n varchar(10)
set @i=0
set @n=0
while @i<1000
begin
set @n=cast(cast(rand()*9999999999 as bigint) as varchar(10))
set @n=REPLICATE('0',10-LEN(@n))+@n
while exists(select * from #t where aa=@n)--如果相同,则重取随机数
begin
set @n=cast(cast(rand()*9999999999 as bigint) as varchar(10))
set @n=REPLICATE('0',10-LEN(@n))+@n
end
insert into #t values(@n)
set @i=@i+1
end
--------
select cast(aa as varchar(10)) from #t
具体进行:declare @i int
declare @d int
declare @n bigint
set @i=1
while @i<=10000
begin
set @n=(SELECT CAST(CEILING(RAND() * 10000000000) AS bigint))
set @d=left(@n,1)
if @d<>8
continue
if @n<1000000000 or exists(select num from #tmp where num=@n) or right(@n,1) in (4,7)
continue
else
begin
insert into #tmp values(@n)
set @i=@i+1
end
end