To generate random number in a single select statement within a range, I always use the below method.
CREATE VIEW vwRandNumber
AS
SELECT RAND() as RandNumber
GO
CREATE function dbo.fnRand() RETURNS FLOAT
AS
BEGIN
RETURN (SELECT RandNumber FROM vwRandNumber)
END
GO
CREATE FUNCTION fn_RandNumber_Int(@Min int, @Max int)
RETURNS INT
AS
BEGIN
RETURN @Min + (select dbo.fnRand()) * (@Max-@Min)
END
GO
CREATE FUNCTION fn_RandNumber_Float(@Min float, @Max float)
RETURNS float
AS
BEGIN
RETURN @Min + (select dbo.fnRand()) * (@Max-@Min)
END
GO
SELECT TOP 10 dbo.fn_RandNumber_Int (10, 200) FROM sys.objects
SELECT TOP 10 dbo.fn_RandNumber_Float (10.1, 200.7) FROM sys.objects
GO
No comments:
Post a Comment