【问题标题】:How to generate alpha number values from a sql query?如何从 sql 查询中生成字母数字值?
【发布时间】:2011-06-21 02:07:36
【问题描述】:

我在我的存储过程中使用以下内容来创建一个 8 位密码并将其作为输出返回。

select @AuthKey = @AuthKey + char(n) from
(
    select top 8 number as n from master.. spt_values
    where type= 'p' and number between 48 and 57
    order by newid()
) as t 

但我希望输出为字母数值,而不仅仅是数值。我怎样才能得到它?

【问题讨论】:

  • 好的,完成... WHERE TYPE='p' and (48 和 57 之间的数字或 65 和 90 之间的数字)
  • 我不完全确定 (spt_values 的使用) 属于时尚与偷偷摸摸的比例......但我有点喜欢它!
  • @Anuya As this blog post notes “不仅可以提出和回答自己的问题,而且明确鼓励这样做。”所以我会说将您的评论移至答案,然后接受它。这也将阻止此问题出现在未回答列表中

标签: sql sql-server-2005 stored-procedures


【解决方案1】:

Anuya——这是一种非常聪明的随机化值的方法,使用order by newid()。如果您的密码区分大小写,您也可以使用小写字符:

declare @AuthKey varchar(255)
set @AuthKey = ''
select @AuthKey = @AuthKey + char(n) from
(
    select top 8 number as n 
    from master..spt_values
    where type= 'p' and (
            (number between 48 and 57)  -- numbers
      or    (number between 65 and 90)  -- uppercase letters
      or    (number between 97 and 122) -- lowercase letters
    )
    order by newid()
) as t 
print @AuthKey

使用稍微不同的方法,您可以包含特定字符集,包括符号:

declare @AuthKey varchar(255), @chars varchar(255), @len int
set @AuthKey = ''
set @chars = '012345ACDFGIJKLMSTXYZ_-#@!'
set @len = len(@chars)

select @AuthKey = @AuthKey + chr.c
from (
    select substring(@chars, num.n, 1) as c
    from (
        select top 8 number as n
        from master..spt_values
        where type='p' and (number between 1 and @len)
        order by newid()
    ) as num
) as chr
print @AuthKey

当然,这仅包括任何给定字符一次。它仍然是一种非常聪明的生成密码的方法。赞一个!

编辑: 如果你想有双打的机会,你可以这样做:

declare @AuthKey varchar(255), @chars varchar(255), @len int
set @AuthKey = ''
set @chars = '012345ACDFGIJKLMSTXYZ_-#@!'
set @len = len(@chars)

SELECT TOP 8 @AuthKey = @AuthKey + SubString(@chars, 1 + Convert(int, ABS(BINARY_CHECKSUM(NewID())) % @len), 1)
  FROM master..spt_values

(也会稍微快一点,因为查询不需要对 spt_values 进行排序。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-08-16
    • 1970-01-01
    • 2013-03-21
    • 2021-11-10
    • 1970-01-01
    • 2015-02-09
    • 2016-12-25
    相关资源
    最近更新 更多