Please start any new threads on our new site at https://forums.sqlteam.com. We've got lots of great SQL Server experts to answer whatever question you can come up with.

 All Forums
 General SQL Server Forums
 Script Library
 How to Implement this as a Function?

Author  Topic 

Transact Charlie
Master Smack Fu Yak Hacker

3451 Posts

Posted - 2007-07-06 : 05:44:15
Hi all,

I've been using a piece of transact code to generate random strings of characters in a lot of scripts and I wanted to wrap it up all nice and neat into a function. I came up with the script below.

However, this fails with the following error..
quote:
Invalid use of 'rand' within a function.

I've allready tried using dynamic sql and sp_executesql inside the function hoping that a new scope would let me use rand() but that isn't allowed either.

I'm Using sql server 2000. Any ideas?

Charlie.

-- snip ----

CREATE FUNCTION dbo.randstr (
@length INT)
RETURNS VARCHAR

AS BEGIN
DECLARE @output VARCHAR(8000)
DECLARE @allowed VARCHAR(8000)

SET @allowed = '234679abcdefghjkmnpqrstuvwxyz234679ACDEFGHIJKLMNPQRTUVWXYZ'

SET NOCOUNT ON
DECLARE @charmap TABLE (charpos INT IDENTITY (1,1), symbol CHAR)
DECLARE @counter INT
DECLARE @character INT
DECLARE @maplength INT

SET @maplength = LEN(@allowed)
SET @character = 0
SET @output = ''

-- Insert the allowed characters into the character map table
SET @counter = 1
WHILE (@counter < @maplength + 1) BEGIN
INSERT INTO @charmap SELECT SUBSTRING(@allowed,@counter,1)
SET @counter = @counter + 1
END

-- Start the loop to generate @output
SET @counter = 1
WHILE (@counter < @length + 1) BEGIN

-- RAND() should output a floating point number between 0 and 1 however...
-- Sometimes the rand() function spits out a number greater than 1
-- or the multiplication results in 0
WHILE (@character < 1) OR (@character > @maplength) BEGIN
SET @character = CAST(@maplength * RAND()+1 AS INT)
END

-- Add the random character to @output
SET @output = @output + (SELECT symbol FROM @charmap WHERE charpos = @character)

-- Increment and Reset the @character variable
SET @counter = @counter + 1
SET @character = 0
END


RETURN @output
END

-- end snip ---

harsh_athalye
Master Smack Fu Yak Hacker

5581 Posts

Posted - 2007-07-06 : 06:02:32
This forum is not for posting questions!

Mods,

I guess there is strong need to change the name of this forum!

Harsh Athalye
India.
"The IMPOSSIBLE is often UNTRIED"
Go to Top of Page

SwePeso
Patron Saint of Lost Yaks

30421 Posts

Posted - 2007-07-06 : 06:03:19
Maybe this?
http://www.sqlteam.com/forums/topic.asp?TOPIC_ID=78859


Peter Larsson
Helsingborg, Sweden
Go to Top of Page

Transact Charlie
Master Smack Fu Yak Hacker

3451 Posts

Posted - 2007-07-06 : 06:25:57
Thankyou for the reply,

And sorry, I plead ignorance (or stupidity) :)


-------------
Charlie
Go to Top of Page
   

- Advertisement -