IF OBJECT_ID ('RandomStr','P') IS NOT NULL
DROP proc RandomStr
go
create proc RandomStr
@RandomStr varchar(6) output
as
BEGIN
declare @s varchar(60)
declare @r varchar(6)
declare @pos int
declare @len int
set @s = '0123456789'
set @len = len(@s);
set @r = ''
while len(@r) < 6
begin
set @pos = cast(rand()*100 as int);
while @pos > @len or @pos <1
begin
if(@pos < 1)
set @pos = cast(rand()*100 as int);
else
set @pos = cast(@pos /2 as int);
end
set @r = @r + substring(@s, @pos, 1)
end
set @RandomStr = @r
END
纯数据的话,以下方式更简单(生成9位以下)
create proc randnum
@len bigint ,--需要的长度
@seed int, --需要的种子
@rand int output--需要的结果
as
begin
declare @rval int
set @len=power(10,@len);
set @rval = rand(@seed)*@len;
while(@rval<(@len)/10)
begin
set @seed=@seed+1;
set @rval = rand(@seed)*@len;
end
set @rand=@rval;
end
--测试
declare @t int,@seed int
set @seed= datepart(ms,getdate());
exec randnum 9,@seed,@t output
print @t
本文介绍了一种使用SQL存储过程来生成指定长度随机字符串的方法。通过创建两个存储过程,一种适用于生成6位数字字母混合字符串,另一种则用于生成指定长度的纯数字随机数。这些过程利用了RAND()函数来确保随机性。

6073

被折叠的 条评论
为什么被折叠?



