获取数据库随机产生的内容

下午一直倒腾数据库的问题。其中有一个问题是随机获取一个表中的数据,而且在规定的时间段内不能更改数据。比如说,这个例子的引用背景是每个月随机产生4个用户,改用户是系统奖励的对象,而且在一个月内改4个用户的信息不变。本然再用一个表就可以轻松实现,但实际要求不能加表,所有只能在一个表内 
set  ANSI_NULLS  ON
set  QUOTED_IDENTIFIER  ON
GO
--  =============================================
--
 Author:        章学敏
--
 Create date: 2007-08-03
--
 Description:    用于随机产生的奖励用户
--
 =============================================
ALTER   PROCEDURE   [ dbo ] . [ Forum_GetAwardUser ]
(
@count   int = 1 , @IsOne   int = 0 , @tempflag   int = 1 , @IsThirthy   int = 0 )
AS
BEGIN     
    
declare   @max   int
    
declare   @rd   int
    
select   top   1   @max = UserID  from  UserBase  order   by   [ CreateTime ]   desc
    
if   exists  ( select  UserID  from  UserBase  where  IsAward = 1 )
        
set   @tempflag = 1
     
if ( @IsThirthy = 1 )
         
begin
             
update  UserBase  set  IsAward = 2   where  IsAward = 1
         
end
    
if   exists  ( select  UserID  from  UserBase  where  IsAward = 2 )
        
set   @tempflag = 2
    
if (( @tempflag = 2 ) and ( @IsOne = 1 ))
        
begin
            
create   table  #td(ID  int , [ Name ]   nvarchar ( 20 ),NName  nvarchar ( 20 ),Photo  varchar ( 300 ))
            
update  UserBase  set  IsAward = 0
            
while   @count < 6
                
begin
                    
select   @rd   =   cast ( ceiling ( rand (checksum( newid ())) * @max as   int )
                    
if   exists ( select  UserID  from  UserBase  where  UserID =   @rd )
                        
begin
                            
set      @count = @count + 1                     
                            
-- select UserID,UserName,Nickname,PhotoUrl from UserBase where UserID=@rd
                             -- insert into #td (ID,[Name],NName,Photo) values (select UserID,UserName,Nickname,PhotoUrl from UserBase where UserID=@rd)
                             insert   into  #td  select  UserID,UserName,Nickname,PhotoUrl  from  UserBase  where  UserID = @rd
                            
update  UserBase  set  IsAward = 1   where  UserID = @rd
                        
end
                    
if   not   exists ( select  UserID  from  UserBase  where  UserID =   @rd )
                        
set   @count = @count
                
end         
            
select   distinct   top   4   *   from  #td  order   by  ID
            
drop   table  #td
        
end
     
else
         
select   top   4  UserID  as  ID,UserName  as   [ Name ] ,Nickname  as  NName,PhotoUrl  as  Photo  from  UserBase  where  IsAward > 0   order   by  UserID
END
以上是存储过程的全部代码,希望各位多多指点!
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值