从列中选择随机值

时间:2013-07-12 20:37:41

标签: sql sql-server

我想清理邮编列上的数据。

到目前为止我已经

declare @postcode table
(
letter1 varchar(4)
,number1 varchar(4)
,number2 varchar(4)
,letter3 varchar(4)
)

insert into @postcode values
('a','1','1','a'),
('b','2','2','b'),
('c','3','3','c')

一直到字母表

(null,'37','37',null)

我的问题是我需要选择一个随机字母,数字然后字母,以便邮政编码看起来像

d12 4RF

我的其余代码如下:

declare @postcodemixup table
                      (ID int identity(1,1)
                       ,Postcode varchar(20))

declare @rand varchar(33)

/*pick a random row and mash it up */
declare @realpostcode varchar (30)

select @realpostcode = letter1 + '' +number1 + ' ' + number1 + '' + letter2 
from @postcode 
where letter1 = 'a'

select @realpostcode

insert into @postcodemixup values(@realpostcode), (@realpostcode)

select * from @postcodemixup

任何答案,阅读材料或建议都会很棒。

谢谢,

3 个答案:

答案 0 :(得分:1)

可能有所帮助的一些事情:

获取1到37之间的随机整数:CONVERT(int, RAND() * 37) + 1

随机收到一封信:CHAR((RAND() * 26) + ASCII('A'))

如果你想要一个随机的行,你可以试试这个,虽然它不会特别快:

declare @rowCount int
    ,   @randomRow int

select @rowCount = COUNT(*) FROM Table1
select @randomRow = RAND() * @rowCount + 1

With A
as  (
  select Table1.*
      ,  rownumber = ROW_NUMBER() OVER (Order BY ID) -- order by something, doesn't matter what
  from   Table1
)
select * 
from   A 
where  rownumber = @randomRow

答案 1 :(得分:1)

不确定这正是您所需要的,但假设所需的公式是"字母数字 - 数字 - 空格 - 数字 - 字母 - 字母" (根据图片),可以生成数据,例如以下声明:

;with
    A as (select cast(char((rand(checksum(newid())) * 26) + ascii('A')) as varchar(10)) A),
    D as (select cast(cast(rand(checksum(newid())) * 10 as int) as varchar(10)) D)
select top (10000)
    row_number() over (order by @@spid) as id,
    A1.A + D1.D + D2.D + ' ' + D3.D + A2.A + A3.A as postcode
from sys.all_columns c1, sys.all_columns c2,
    A A1, D D1, D D2, D D3, A A2, A A3

答案 2 :(得分:0)

如果您的随机邮政编码必须基于@postcode表中预定义的值,请尝试以下查询:

set @realpostcode = (select top 1 letter1 from @postcode order by NEWID()) + 
                (select top 1 number1 from @postcode order by NEWID()) +
                (select top 1 number2 from @postcode order by NEWID()) +
                (select top 1 letter2 from @postcode order by NEWID())