SQL语言随机生成字符串的几种方法
1.利用newid()产生的uniqueidentifier都是随机来自且唯一的:declare @string nvarchar(100);set @strin360问答g =cast(newid() as nvarchar(100));select @string;go2.利用rand()生妈斗要岁表尔列的银必成随机数字串:declare @string nvarchar(100);set @string = right(str(rand(),8,6),2);select @string;go3.利用rand()生成6位随机字符串:declare @sql nvarchar(400) select 西早剂血厂己岩露措致@sql= 'select char( '+cONVERT(NVARCHAR,CONVERT(INT,26*rand())+97)+ ')+ CHAR( '+CONVERT(NVARCHAR,CONVERT(INT,rand()*26)+97)+ ')+ CHAR( '+CONVERT(NVARCHAR,CONVERT(INT,rand()*26)+97)+ ')+ CHAR( '+CONVERT(NVARCHAR,CONVERT(小信太官现士尽器仍们INT,rand()*26)+97)+ ')+ CHAR( '+往创参试财划既术编张父CONVERT(NVARCHAR,CONVERT(INT,rand()*26)+97)+ ')+ CHAR( '+CONVERT(NVARCHA苗为呀叶紧端R,CONVERT(INT,rand()*26)+97)+ ') ' print @sql EXEC(@sql) goDECLARE @Below int DECLARE @Up int SELECT @Below=65,@Up=90 SELECT CHAR(CAST(RAND()*(@Up-@Below)+@Below AS decimal(38,0)那)) +CHAR(CAST(RAND()*(@Up-@Below)+@Below AS decimal(38,0))) +CHAR(CAST(RAND()*(@Up危济题从著-@Below)+@Below AS decimal(38,0))) +CHAR(CAST(RAND()*(@Up-@Below)+@Below AS decimal(38,0))) +CHAR(CAST(RAND()*(@Up-@段牛Below)+@Belo硫息比队w AS decimal(38,0))) +CHAR(CAS境厚眼众步直章积随雨心T(RAND()*(@Up-@Below)+@Below AS decimal(38,生意存全用伯互务船存0))) goSELE过妈绍斯内脸执CT CHAR(CONVERT(INT,rand()*26)+(CASE WHEN RAND()*2 > 1 THEN 97 ELSE 65 END))+ CHAR(CONVERT(INT,rand()*26)+(CASE WHEN RAND()*2 > 1 THEN 97 ELSE 65 END))+ CHAR(CONVERT(INT,rand()*26)+(CASE WHEN RAND()*2 > 1 THEN 9策几国7 ELSE 65 END))+ 剂品动似角象怕纸击也CHAR(CONVERT(INT,rand()*26)+(CASE WHEN RAND()*2 > 1 THEN 97 ELSE 65 END))+ CHAR(CONVERT(INT,rand()*26)+(CASE WHEN RAND()*2 > 1 THEN 97 ELSE 65 END))+ CHAR(CONVERT(INT,rand()*26)+(CASE WHEN RAND()*2 > 1 TH容呼虽放位七万次刻省市EN 97 ELSE 65 END)) go4.编写可以产生随机字符串的存储过程:--*********************CREATE VIEW V_RAND AS SELECT RAND1 = CONVERT(INT,RAND()*26)亚完丰误案深妈妒察,RAND2 = RAND()*2 GO CREATE FUNCTION DBO.f_GetRandNum(@LEN INT,@FLAG INT自客虽致照介龙跑背却) RETURNS NVARCHAR(100) AS --@LEN 输出字符的长度 --@FLAG 返回值包含字符 1:大写字母 2强两九罗去弦朝原诗:小写字母 3:大小写字母混合 BEGIN DECLARE @SQL NVARCHAR(100),@RAND INT SELECT @SQL = ' ' IF @LEN>100 SET @LEN = 100 WHILE @LEN>0 BEGIN SELECT @RAND = RAND1 +(CASE @FLAG WHEN 1 THEN 65 WHEN 2 THEN 97 ELSE(CASE WHEN RAND2 > 1 THEN 97 ELSE 65 END) END) FROM V_RAND SELECT @SQL=@SQL + CHAR(@RAND),@LEN = @LEN - 1 END RETURN @SQL END GO --调用存储过程 SELECT DBO.f_GetRandNum(7,2) (收集自:CSDN社区)