SQL生成随机字符串

创建存储过程可以解决此问题

 1 Create PROCEDURE [dbo].[Test]
 2 @Len int,--生成字符串的长度
 3 @Type int--生成字符串的类型 1:全数字, 2:全大写字母,3:全小写字母,4:数字+大写字母+小写字母组合
 4 AS
 5 BEGIN
 6 declare @rand1 int;--用于判断是获取字符串类型 1:数字,2:大写字母,3:小写字母,4:数字/大写字母/小写字母
 7 declare @rand2 int;--用户获取随机数,拼接字符串
 8 declare @rand int;--拼接后转为ASCII的数字
 9 declare @returnStr nvarchar(100); set @returnStr=''
10 
11 if(@Type=1) begin set @rand1=1 end;
12 if(@Type=2) begin set @rand1=2 end;
13 if(@Type=3) begin set @rand1=3 end;
14 while(@Len>0)
15 begin
16 if(@Type=4) 
17 begin 
18 --RAND() 生成随机0到1之间的数字
19 --CEILING() 向上取整
20 set @rand1=CONVERT(INT, CEILING(RAND()*3)) 
21 end;
22 --FLOOR() 向下取整
23 set @rand2= CONVERT(INT, FLOOR(RAND()*26));
24 set @rand=case @rand1 when 1 then CONVERT(INT, FLOOR(RAND()*10))+48 
25 when 2 then @rand2+ 65
26 else @rand2+ 97 end
27 set @returnStr=@returnStr+char(@rand);
28 set @Len=@Len-1
29 end
30 select @returnStr as randstr into #temp
31 select * from #temp
32 END
33 
34 
35 --select char(48),char(49),char(57) ---48-57 (数字) 10个
36 --select char(65),char(66),char(90) --65-90 (大写) 26个
37 --select char(97),char(98),char(122) --97-122 (小写) 26个
View Code

 

posted @ 2019-06-21 17:25  EnjoyToday  阅读(620)  评论(0编辑  收藏  举报