SQL 生成随机编号

SQL-CODEALTER FUNCTION [dbo].[f_RANDBH](@BHLen int)
RETURNS varchar(50)
AS
BEGIN
 DECLARE @r varchar(50)
 IF NOT(ISNULL(@BHLen,0) BETWEEN 1 AND 50)
  SET @BHLen=10
 SELECT @r=CHAR(
   CASE WHEN SUBSTRING(re,1,1)>5 THEN 97 ELSE 65 end
   +(SUBSTRING(re,1,1)
   +SUBSTRING(re,2,1)
   +SUBSTRING(re,3,1))%26)
  +CHAR(
   CASE WHEN SUBSTRING(re,4,1)>5 THEN 97 ELSE 65 end
   +(SUBSTRING(re,4,1)
   +SUBSTRING(re,5,1)
   +SUBSTRING(re,6,1))%26)
 FROM v_RAND
 WHILE LEN(@r)<@BHLen
  SELECT @r=@r+CHAR(
    CASE WHEN SUBSTRING(re,1,1)>5 THEN 97 ELSE 65 end
    +(SUBSTRING(re,1,1)
    +SUBSTRING(re,2,1)
    +SUBSTRING(re,3,1))%26)
   +CHAR(
    CASE WHEN SUBSTRING(re,4,1)>5 THEN 97 ELSE 65 end
    +(SUBSTRING(re,4,1)
    +SUBSTRING(re,5,1)
    +SUBSTRING(re,6,1))%26)
  FROM v_RAND
 SET @r = LEFT(@r,@BHLen)
 SET @r = @r+REPLACE(REPLACE(REPLACE(CONVERT(VARCHAR, GETDATE(), 120 ),':',''),'-',''),' ','') 
 RETURN(@r)
END
--执行示例
SELECT [dbo].[f_RANDBH](NULL)SELECT [dbo].[f_RANDBH](NULL)
--执行结果
DWihcunCUz20090828081450D
大部分代码转载邹建SQL教程,自己也根据需要略有一点点改动!
posted on 2009-08-28 08:16  ToKens  阅读(596)  评论(0编辑  收藏  举报