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

来源:互联网 发布:手机易拉宝制作软件 编辑:程序博客网 时间:2024/05/06 17:26
下午一直倒腾数据库的问题。其中有一个问题是随机获取一个表中的数据,而且在规定的时间段内不能更改数据。比如说,这个例子的引用背景是每个月随机产生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()))*@maxas 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
以上是存储过程的全部代码,希望各位多多指点!
原创粉丝点击