/*
我想问一个SQL语句
F_Id F_Name
1 张三
2 李四
3 王五
这是数据库中的数据
前提是我查找数据的时候,每次都只显示两行数据,同时id=1的这行数据一直存在,另外两行数据随机的显示
*/
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_NULLS ON
GO
alter proc GetRecordsByRand
as
begin
/*
定义存储过程所需变量
@all 保存要抽取记录的表的记录条数
@b_id 临时变量
@e_id 临时变量
*/
declare @all int
declare @b_id int
set @b_id=0
declare @e_id int
set @e_id=0
declare @str varchar(20)
/*
将可用于随机抽取的记录放入临时表
*/
CREATE TABLE #table (sys_id int IDENTITY (1, 1) NOT NULL ,F_Id int )
insert into #table (F_Id)
select F_Id from t_Table where F_Id<>1
--得到总共有多少记录
select @all=max(sys_id) from #table
/*
循环给两个临时变量随机赋值,直到两个变量值不一样为止
附注:实际上这里是先将主表的主键和临时表的主键关联起来,然后随机抽取临时表主键值
,再通过随机获取的临时表主键关联到主表主键,获取记录!
*/
while(@b_id=@e_id)
begin
select @b_id=cast(rand()*@all as int),@e_id=cast(rand()*@all as int)
end
--得到最终结果集
select * from t_Table where F_Id=1
union
select * from t_Table where F_Id in (select F_Id from #table where sys_id=@b_id or sys_id=@e_id)
--删除临时表
drop table #table
end
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO