Try this:
select Rand1.n as RandomIntegerBetweenAB
, Rand2.n as RandomIntegerBetweenXY
, DateAdd(Day, Rand3Rand2.n, GetDate()) as RandomDateBetweenABRandomDateAddBetweenXY
, Rand4Rand3.n as RandomInteger
from api.RandomIntBetween(0, 100) as Rand1
cross apply api.RandomIntBetween(-50, 25) as Rand2
cross apply api.RandomIntBetween(-365, 365) as Rand3Rand2
cross apply api.RandomIntBetween(default, default) as Rand4;Rand3;
We use this view to generate a random integer (only because SQL Server won't simply let us use Crypt_Gen_Random()
in a UDF):
create view api.vw_RandomInt
with schemabinding
as (
select Cast(Crypt_Gen_Random(4) as int) as n
);
Using this view as a base we can get whatever random integer and then do some maths to rescale it:
create function api.RandomIntBetween (
@x int = -2147483648
, @y int = 2147483647
)
returns table
with schemabinding as
return (
select Cast(Round(c.f, 0, 0) as int) as n
from (values(
case when @x < @y then @x else @y end
, case when @y > @x then @y else @x end
)) a ([Min], [Max])
cross join api.vw_RandomInt as b
cross apply api.NormalizeBetween(
b.n
, -2147483648
, 2147483647
, a.[Min] - 0.5
, a.[Max] + 0.5
) as c
);
Where the definition of NormalizeBetween is:
create function api.NormalizeBetween (
@f float = 1.
, @x float = 0.
, @y float = 1.
, @a float = 0.
, @b float = 1.
)
returns table
with schemabinding as
return (
select ((@f - @x) * (@b - @a)) / NullIf(@y - @x, 0) + @a as f
);