我想产生1到10的随机数字,但这些数字,不能是a表的中id列的值。
a表结构如下:
id   name
1    hjt
3    wjb
2    lp
3    zrj
 
现在产生的随机数字可以为:4,5,6,7,8,9其中的一个

解决方案 »

  1.   

    select cast(rand()*10 as int)
      

  2.   

    但产生的数字,不能是a表中的id 列的值啊
      

  3.   

    select top 10 id=identity(int,1,1) into #t from syscolumns
    declare @i int
    select top 1 @i=id from #t 
    where id not in(select id from a)
    order by newid()
    print @i
    drop table #t
      

  4.   

    select top 1 id from (select 1 as 'id'
    union select 2
    union select 3
    union select 4
    union select 5
    union select 6
    union select 7
    union select 8
    union select 9
    union select 10)t
    where t.id not in (select distinct id from a表)
    order by newid()
      

  5.   

    create table tb(id int)
    insert into tb(id) values(1)
    insert into tb(id) values(2)
    insert into tb(id) values(3)declare @i as int
    declare @j as int
    select @i = cast(rand()*10 as int)select @j = id from tb where id = @i
    if @j is null
       print 'i = ' + cast(@i as varchar) + ' ,不存在'
    else
       print 'i = ' + cast(@i as varchar) + ' ,存在'drop table tb--
    i = 2 ,存在i = 4 ,不存在
      

  6.   

    select top 10 id=identity(int,1,1) into #t from syscolumns
    declare @i int
    select top 1 @i=id from #t 
    where id not in(select id from a)
    order by newid()
    print @i
    drop table #t这个不错
      

  7.   

    playwarcraft(时间就像乳沟,挤挤还是有的) 的不错
      

  8.   

    create table [b] (
    [randid] [int] null
    ) on [primary]
    GOdeclare @i int,@j int,@n int,@k int
    set @k=1
    select @n=count(distinct(id)) from a
    set @i=0
    while @k<=@nbegin
    if @i<>1begin
    insert into b(randid) select cast(rand()*10 as int) as randidselect @j=randid from b
    select @i=count(randid) from b where randid not in (select id from a)
    endelsebegin
    delete from b
    endset @k=@k+1
    end
    select @j
      

  9.   

    create table t1(key_sep int)declare @min int,@max int,@value int
    set @max=10
    set @min=1
    set @value=ceiling((@max-@min)*rand())+@min
    if exists (select 1 from t1 where key_sep=@value)
     begin
     return
     end
    else
    insert into t1(key_sep) select  @value