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
3条答案
按热度按时间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:
Then you can use this view in the function:
Then just use it directly:
lyr7nygr2#
Unless you explicitly need a function, you can just do this with a view:
Note: This does use a slightly different method to generate the random number.
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:
After which you can call it with