create proc proc_gen_randomstr(@strlen int)
as
begin
-- 最多生成50位,根据返回值长度设定
set @strlen = case when @strlen > 50 then 50 else @strlen end;
-- 字符位数标识
declare @i int=1
-- 随机生成标识
declare @flag int=1
-- 最终生成的随机字符串
declare @randomstr nvarchar(50)=''
while( @i <= @strlen )
begin
--随机标识,这个随机标识会随机选中生成大写字母,小写字母或者数字
set @flag=ceiling(rand()*3)
if @flag=1
begin
--随机字母(大写)
set @[email protected]+char(65+ceiling(rand()*25))
end
else if @flag=2
begin
--随机字母(小写)
set @[email protected]+char(97+ceiling(rand()*25))
end
else
begin
--随机数字 1至9的随机数字(整数)
set @[email protected]+cast(floor(rand()*(10)) as nvarchar(1))
end
set @[email protected]+1
end
select @randomstr as randomstr;
end