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
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