SqlServer 产生随机数

ALTER PROCEDURE [dbo].[usp_RandomNumber] 
( 
@Len INT = 1, --随机数位数 
@Rows INT = 1 --随机笔数 
) 
AS 
BEGIN 
DECLARE @T AS TABLE([Random Number] VARCHAR(MAX)) 
DECLARE @L INT = 1, @R INT = 1 
WHILE @R <= @Rows 
BEGIN 
DECLARE @RN varchar(MAX) = '' 
WHILE @L <= @Len --随机产生每个随数的位数 
BEGIN 
SET @RN = @RN + CHAR(ROUND(RAND() * 9 + 48,0)) 
SET @L = @L + 1 
END 
--如果产生相同的随机数,将不会存储 
IF NOT EXISTS(SELECT [Random Number] FROM @T WHERE [Random Number] = @RN) 
BEGIN 
INSERT INTO @T SELECT @RN --INSERT INTO @T ([Random Number])VALUES (@RN) 
SET @R = @R + 1 --记录总共产生了几笔随机数 
SET @L = 1 -- 每产生完一个随机数之后,将随机数的位数初始化为1 
END 
END 
Return @RN 
END 

调用:

EXECUTE [dbo].[usp_RandomNumber] 8,1

 

posted on 2015-12-21 10:41  花生哒哒  阅读(2500)  评论(0编辑  收藏  举报

导航