--首先创建下面的函数--自定义函数:取得指定上下限的随机数if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[f_rand]') and xtype in (N'FN', N'IF', N'TF'))
drop function [dbo].[f_rand]
GO
if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[v_rand]') and OBJECTPROPERTY(id, N'IsView') = 1)
drop view [dbo].[v_rand]
GO--需要这样一个视图
create view v_rand as select re=rand()
go--自定义函数:取得指定上下限的随机数
create function f_rand(
@下限 int,
@上限 int
)
returns decimal(38,0)
as
begin
declare @r decimal(38,0)
select @r=cast(re*(@上限-@下限)+@下限 as decimal(38,0)) from v_rand
return(@r)
end
go--调用示例
select dbo.f_rand(10,100),dbo.f_rand(10,100)

解决方案 »

  1.   

    --然后,调用上述函数生成随机数:declare @rowcount int,@i int
    create table #t(id int identity(1,1),随机数 int constraint aa unique)select @rowcount=1000 --生成10000条记录
    ,@i=@rowcountinsert #t select distinct dbo.f_rand(1,@rowcount) from syscolumns
    set @i=@i-@@rowcount
    while @i>0
    begin
    insert #t select distinct dbo.f_rand(1,@rowcount) from sysobjects
    set @i=@i-@@rowcount
    end--显示生成的结果
    select * from #tdrop table #t
      

  2.   

    -- 可处理1--10000的数据
    select id from (
    select id=a.id+b.id*10+c.id*100+d.id*1000+e.id*10000+1 from 
    (
    select id=0 union all select 1
    union all select id=2 union all select 3
    union all select id=4 union all select 5
    union all select id=6 union all select 7
    union all select id=8 union all select 9
    ) a,(
    select id=0 union all select 1
    union all select id=2 union all select 3
    union all select id=4 union all select 5
    union all select id=6 union all select 7
    union all select id=8 union all select 9
    ) b,(
    select id=0 union all select 1
    union all select id=2 union all select 3
    union all select id=4 union all select 5
    union all select id=6 union all select 7
    union all select id=8 union all select 9
    ) c,(
    select id=0 union all select 1
    union all select id=2 union all select 3
    union all select id=4 union all select 5
    union all select id=6 union all select 7
    union all select id=8 union all select 9
    ) d,(
    select id=0 union all select 1
    union all select id=2 union all select 3
    union all select id=4 union all select 5
    union all select id=6 union all select 7
    union all select id=8 union all select 9
    ) e
    ) aa
    -- where id <= 最大值  --如果需要上限,加上此条件即可
    order by newid()
      

  3.   

    我自己解决啦~~
    方法是新增一个临时字段,给这个临时字段赋rand(),然后按照这个字段排序
    然后从1开始递增赋值