IF EXISTS ( SELECT * 
            FROM   sysobjects 
            WHERE  id = object_id(N'dbo.CF_Token')  and type = 'FN')
BEGIN
    DROP FUNCTION dbo.CF_Token
	DROP VIEW rndView
END
GO


CREATE VIEW rndView
AS
SELECT RAND() rndResult
GO



CREATE FUNCTION dbo.CF_Token(@tam SMALLINT)
RETURNS VARCHAR(1024)
AS
BEGIN

DECLARE @pos SMALLINT
	,@SourceString CHAR(62)
	,@Retorno VARCHAR(1024)
	,@Car CHAR(1)
	,@rndValue FLOAT


SET @SourceString = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz'
SET @Retorno = ''

SET @pos = 1
WHILE (@pos < @tam + 1)
BEGIN
	SELECT @rndValue = rndResult FROM rndView
	SET @Car = SUBSTRING(@SourceString,CAST( ROUND(@rndValue * 62,0) AS INT),1)
	SET @Retorno = LTRIM(RTRIM(@Retorno)) + @Car
	SET @pos = @pos + 1
END

RETURN @Retorno


END

