2013-07-12 119 views
0

我想清除郵編列上的數據。從列中選擇隨機值

到目前爲止,我有

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 

任何答案,閱讀材料或建議將是偉大的。

謝謝

周杰倫

+0

所以基本上你需要創建一個varchar與隨機letter1 + number1 + number2 + letter2? –

+0

所以你只需要一個隨機的nuber生成器? –

回答

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

i-one - 太棒了!非常感謝你。 – Jay

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

謝謝你的答案(儘管Ann L--你的頭已經過去了,我還是很初級的!)。我需要它爲我指定的行生成一個隨機郵編。 所以我的結果像http://oi42.tinypic.com/i2q0z8.jpg – Jay

+0

不客氣!很高興你解決了問題! –

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