Sometime you may want to return a random number for each row. You can not do this directly selecting a RAND() function in query:
SELECT Rand() AS Random_Number, Name, Code from MyTable.
The above query will return the same random number for each row.
But you want to select different random number for each row. Follow below steps to do so:
create view rand_view
as
select rand( ) as random_value
go
create function New_rand()
returns float
as
begin
declare @f float
set @f = (select random_value from rand_view)
return @f
end
SELECT dbo.New_rand() wrapped_rand, Name, Code FROM MyTable
SELECT Rand() AS Random_Number, Name, Code from MyTable.
The above query will return the same random number for each row.
But you want to select different random number for each row. Follow below steps to do so:
create view rand_view
as
select rand( ) as random_value
go
create function New_rand()
returns float
as
begin
declare @f float
set @f = (select random_value from rand_view)
return @f
end
SELECT dbo.New_rand() wrapped_rand, Name, Code FROM MyTable
No comments:
Post a Comment