You can use the row_number
function that assigns a row number based on aggregation or sorting, and use the newid
function as sorting, which generates a unique value for each row every time query
is executed:
select row_number() over(order by newid()) as randomico1,
row_number() over(order by newid()) as randomico2,
ra
from saluno
order by ra
The query
above does not work using the top
clause. If you need to use it, you must subquery
with top
before generating the random column as follows:
select row_number() over(order by newid()) as randomico1,
row_number() over(order by newid()) as randomico2,
x.ra
from (select top(10) tb.*
from saluno tb) x
order by x.ra
If you want to use the same value for another column more than once, you can also use subquery
:
select x.randomico1,
x.randomico1 as randomico2,
x.ra
from (select row_number() over(order by newid()) as randomico1,
tb.*
from saluno tb) x
order by x.ra
Or:
select row_number() over(order by x.aleatorio) as randomico1,
row_number() over(order by x.aleatorio) as randomico2,
x.ra
from (select newid() as aleatorio,
tb.*
from saluno tb) x
order by x.ra
If you want a random number that is unrelated to the number of rows, use the following query
where the number after %
is the maximum:
select abs(checksum(newid()) % 10) + 1 as randomico1,
ra
from saluno
Or using for the two random columns:
select x.aleatorio as randomico1,
x.aleatorio as randomico2
from (select cast(rand(checksum(newid())) * 10 as int) + 1 as aleatorio,
tb.*
from saluno tb) x
order by x.ra