SQL Server T-SQL function that return random huge Int

qaxu7uf2  于 2023-04-19  发布在  其他
关注(0)|答案(3)|浏览(107)

I need to prepare function that will return random quite a huge int. I'm using "huge" adjective to not mix with bigint.

CREATE FUNCTION fn_RandomHugeInt() 
RETURNS int 
AS
BEGIN 
    RETURN (SELECT ABS(CHECKSUM(NEWID()) % (2147483647 - 2000000000 + 1)) + 2000000000)
END

SELECT fn_RandomHugeInt()

Unfortunately it seems that that such code doesn't work

yc0p9oo0

yc0p9oo01#

The use of newid() is not permitted in a function, which you probably noticed.

There is a slightly covert workaround however.

First create a view:

create or alter view getNewID 
as select newid() as NewId;

Then you can use this view in the function:

create or alter function fn_RandomHugeInt() 
returns int 
as
begin 
  return (
    select abs(checksum(NewId) % (2147483647 - 2000000000 + 1)) + 2000000000 
    from getNewId
  );
end

Then just use it directly:

select dbo.fn_RandomHugeInt();
lyr7nygr

lyr7nygr2#

Unless you explicitly need a function, you can just do this with a view:

CREATE OR ALTER VIEW RandomHugeInt
AS
SELECT ROUND(((2147483647  - 2000000000 ) * (RAND(CONVERT(VARBINARY,NEWID(),1))) + 2000000000), 0) AS Rnd
GO

SELECT *
  FROM RandomHugeInt a
    CROSS APPLY RandomHugeInt b
    CROSS APPLY RandomHugeInt c
    CROSS APPLY RandomHugeInt d

Note: This does use a slightly different method to generate the random number.

jhdbpxl9

jhdbpxl93#

The error you're getting is presumably:
Invalid use of a side-effecting operator 'newid' within a function.

I'm not sure exactly what is being affected here, but I'm not going to fight a robot. You can get around this with the following change:

CREATE OR ALTER FUNCTION dbo.fn_RandomHugeInt(@id uniqueidentifier)
RETURNS int as
BEGIN
    return (select ABS(CHECKSUM(@id) % (2147483647 - 2000000000 + 1)) + 2000000000)
END

After which you can call it with

SELECT dbo.fn_RandomHugeInt(NEWID());

相关问题