sql server 中取十位随机字符串

———————-字符串中有重复的字符——————–
declare @l int
declare @s varchar(26)
declare @r varchar(200)
set @l = 10 ———–设置返回长度,最大长度受@r的限制
set @s = ‘abcdefghijklmnopqrstuvwxyz’
set @r = ”
while len(@r) < @l
begin
set @r = @r + substring(@s, cast(rand() * 100 as int) % 26 +1 , 1)
end
print @r

——————–字符串中无重复字符———————————-

declare @s varchar(26)
declare @r varchar(8)
declare @t varchar(1)
set @s = ‘abcdefghijklmnopqrstuvwxyz’
set @r = ”

while len(@r) < 8
begin
set @t = substring(@s, cast(rand() * 100 as int) % 26 +1 , 1)
if charindex(@t, @r) < 1
set @r = @r + @t
end
print @r

——————–字符串中无重复字符函数———————————-
ALTER FUNCTION dbo.GetRandStr
(@Count INTEGER = 8)
RETURNS VARCHAR
AS
BEGIN
DECLARE @STR VARCHAR(100), @STR1 VARCHAR(36)
DECLARE @I INTEGER, @J INTEGER, @M INTEGER, @N INTEGER
SET @STR1 = ‘0123456789abcdefghijklmnopqrstuvwxyz’
SET @I = 1
SET @M = 1
SET @STR = ”
WHILE @I <= 36
BEGIN
HERE:
SET @M = CAST(dbo.RAND() * 100 / 2.75 AS INTEGER)
IF (@M < 1) OR (@M = @N) OR (CHARINDEX(SUBSTRING(@STR1, @M ,1), @STR)) > 0 GOTO HERE
SET @N = @M
SET @STR = @STR + SUBSTRING(@STR1, @M ,1)
SET @I = @I + 1
END
RETURN @STR
END

发表评论

电子邮件地址不会被公开。 必填项已用*标注