1

Possible Duplicate:
Creating Nondeterministic functions in SQL Server using RAND()

I need to generate some random nvarchar in a function. So I create this function :

CREATE FUNCTION [dbo].[sfp_GenerateRandomString]    
    (@length int) -- Length of string   
RETURNS NVARCHAR
AS
BEGIN
DECLARE @random NVARCHAR(25) = ''

while @length > 0   
begin
    set @random = @random + nchar((cast(rand()*1000 as int)%26)+97)
    set @length = @length-1
end
return @random      
END

But it doesn't work because the RAND() function is forbidden in SQL function who have to be DETERMINISTIC. And RAND() is NONDETERMINISTIC.

So my question is how to generate random number in this case? Thanks.

Community
  • 1
  • 1
bAN
  • 13,375
  • 16
  • 60
  • 93

1 Answers1

0

You could use a SQL CLR function if you really needed it in a function. Or if you only need it in one place, just put it in the stored procedure.

Personally I would opt towards not doing this sort of work inside SQL Server at all, if it could be helped. This is application logic, not database logic. Although without knowing the back story, I don't know what other constraints you may have.

DaveShaw
  • 52,123
  • 16
  • 112
  • 141
  • Thanks, I need this in a sql function because it is not dependent of the application. It is for a data obfuscation script to allow to share the database – bAN Nov 28 '11 at 10:55