自制根据数量返回随机的员工姓名存储过程

USE [******]
GO
/****** 对象:  StoredProcedure [dbo].[ttt]    脚本日期: 03/24/2018 08:10:14 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
ALTER proc [dbo].[ttt] (@ts int)
as 
begin 
declare @sl int
DECLARE @randomInt INT
 DECLARE @i INT
if exists(select * from tempdb..sysobjects where id=object_id('tempdb..##temptm'))
drop table ##temptm
create table ##temptm
(
id int

)


select @sl=count(*) from Emp_BaseInfo


  SET @i=0
        WHILE @i<@ts
        BEGIN
              select @randomInt=CEILING(rand()*@sl) 
                 
          
          --不能是 SET @randomInt=SELECT random FROM v_random
          IF NOT EXISTS(SELECT TOP 1 * FROM ##temptm WHERE id=@randomInt)
           BEGIN
             INSERT INTO ##temptm VALUES (@randomInt)
             SET @i=@i+1
           END
        END


 select ROW_NUMBER() over(order by emp_code) as id,  emp_code,emp_name from Emp_BaseInfo where Emp_id IN(select ID from ##temptm)


end

你可能感兴趣的:(SQL)