“大哥,看了你这篇博文http://www.cnblogs.com/insus/archive/2012/01/27/2330058.html,我怎样才能产生10个且每个有8位不相同的随机数字?”
刚才有位网友在SKYPE问及如上问题。
好的,Insus.NET也正想写一个存储过程来应用上面这篇的SQL语句,你可以参考如下的存储过程,如果还问题请继续讨论。View Code
CREATE PROCEDURE [dbo].[usp_RandomNumber]
( 1 CREATE PROCEDURE [dbo].[usp_RandomNumber]
2 (
3 @Len INT = 1, --随机数位数
4 @Rows INT = 1 --随机笔数
5 )
6 AS
7 BEGIN
8 DECLARE @T AS TABLE([Random Number] VARCHAR(MAX))
9 DECLARE @L INT = 1, @R INT = 1
10
11 WHILE @R <= @Rows
12 BEGIN
13 DECLARE @RN varchar(MAX) = ''
14 WHILE @L <= @Len --随机产生每个随数的位数
15 BEGIN
16 SET @RN = @RN + CHAR(ROUND(RAND() * 9 + 48,0))
17 SET @L = @L + 1
18 END
19
20 --如果产生相同的随机数,将不会存储
21 IF NOT EXISTS(SELECT [Random Number] FROM @T WHERE [Random Number] = @RN)
22 BEGIN
23 INSERT INTO @T SELECT @RN --INSERT INTO @T ([Random Number])VALUES (@RN)
24 SET @R = @R + 1 --记录总共产生了几笔随机数
25 SET @L = 1 -- 每产生完一个随机数之后,将随机数的位数初始化为1
26 END
27 END
28
29 SELECT [Random Number] FROM @T
30
2 (
3 @Len INT = 1, --随机数位数
4 @Rows INT = 1 --随机笔数
5 )
6 AS
7 BEGIN
8 DECLARE @T AS TABLE([Random Number] VARCHAR(MAX))
9 DECLARE @L INT = 1, @R INT = 1
10
11 WHILE @R <= @Rows
12 BEGIN
13 DECLARE @RN varchar(MAX) = ''
14 WHILE @L <= @Len --随机产生每个随数的位数
15 BEGIN
16 SET @RN = @RN + CHAR(ROUND(RAND() * 9 + 48,0))
17 SET @L = @L + 1
18 END
19
20 --如果产生相同的随机数,将不会存储
21 IF NOT EXISTS(SELECT [Random Number] FROM @T WHERE [Random Number] = @RN)
22 BEGIN
23 INSERT INTO @T SELECT @RN --INSERT INTO @T ([Random Number])VALUES (@RN)
24 SET @R = @R + 1 --记录总共产生了几笔随机数
25 SET @L = 1 -- 每产生完一个随机数之后,将随机数的位数初始化为1
26 END
27 END
28
29 SELECT [Random Number] FROM @T
30
@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
SELECT [Random Number] FROM @T
END
当你把上面的存储过程附加入数据库之后,可以执行这个存储过程:
EXECUTE [dbo].[usp_RandomNumber] 8,10
得到的结果(由于是随机产生,每次execute获得结果会不一样)
http://www.cnblogs.com/insus/archive/2012/01/27/2330104.html