I am using the function below to generate a random number between 0 and 99999999999.
CREATE VIEW [dbo].[rndView]
AS
SELECT RAND() rndResult
GO
ALTER function [dbo].[RandomPass]()
RETURNS NUMERIC(18,0)
as
begin
DECLARE @RETURN NUMERIC(18,0)
DECLARE @Upper NUMERIC(18,0);
DECLARE @Lower NUMERIC(18,0);
DECLARE @Random float;
SELECT @Random = rndResult
FROM rndView
SET @Lower = 0
SET @Upper = 99999999999
set @RETURN= (ROUND(((@Upper - @Lower -1) * @Random + @Lower), 0))
return @RETURN
end;
However, I need to make sure that the returned number has never been used before in the same app. In .net I would create a while loop and keep looping until the returned value is not found in a table that stores previously used values. Is there a way to achieve the same result directly in SQL, ideally without using loops? If there is no way to do that without loops, I think it would still be more efficient to do it in an SQL function rather than having a loop in .net performing a number of query requests.
Aucun commentaire:
Enregistrer un commentaire