“大哥,看了你这篇博文http://www.cnblogs.com/insus/archive/2012/01/27/2330058.html,我怎样才能产生10个且每个有8位不相同的随机数字?”
刚才有位网友在SKYPE问及如上问题。
好的,Insus.NET也正想写一个存储过程来应用上面这篇的SQL语句,你可以参考如下的存储过程,如果还问题请继续讨论。
usp_RandomNumber
CREATE
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
SELECT [ Random Number ] FROM @T
END
(
@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获得结果会不一样)