I want to cleanse data on the postcode column.
So far I have
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')
All the way down the alphabet to
(null,'37','37',null)
My problem is that I need to select a random letter, number then letter so the postcode turns up looking something like
d12 4RF
The rest of my code is below:
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
Any answers, reading material or suggests would be great.
Thank you,
Jay
Some things that may help:
To get a random integer between 1 and 37: CONVERT(int, RAND() * 37) + 1
To get a random letter: CHAR((RAND() * 26) + ASCII('A'))
If you want a random row, you could try this, though it wouldn't be particularly speedy:
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
Not sure this is exactly what you need, but assuming the formula needed is "letter-digit-digit-space-digit-letter-letter" (according to picture), data can be generated eg with the following statement:
;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
If your random postcode must be based values, predefined in the @postcode table, try this query:
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())
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.