创建SQL函数时出错

时间:2014-07-28 14:51:17

标签: sql-server tsql

我正在创建一个SQL函数(MS-SQL),用于在sproc中创建随机长度的随机字符串。当我写出整个函数时,Create Function行得到了厄运的红线,声称“语法不正确:创建函数必须是批处理中的唯一语句。”

代码如下:

Create Function dbo.randomtesttext (@length int)
returns varchar(999)
as
Begin
    declare @pool varchar
    set @pool = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890'
    declare @return varchar(999)
    declare @position int = 0
    while (@position < @length)
    begin
        set @return = @return + (select substring(@pool, convert(int, rand()*36), 1))
        set @position = @position + 1
    end
    return @return
end

有什么想法?我确定答案很简单,我只是没有足够的经验来看。

2 个答案:

答案 0 :(得分:1)

您不能在用户定义的函数中使用RAND内置函数。无论如何,您可以使用以下解决方法将RAND放在视图中:

CREATE VIEW rndView
AS
SELECT RAND() rndResult
GO

然后在你的函数中调用它:

Create Function dbo.randomtesttext (@length int)
returns varchar(999)
as
Begin
    declare @pool varchar
    set @pool = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890'
    declare @return varchar(999)
    declare @position int = 0
    while (@position < @length)
    begin
        set @return = @return + (select substring(@pool, convert(int, rndResult*36), 1) FROM rndView)
    end
    return @return
end

答案 1 :(得分:0)

Create View rndView
as 
SELECT RAND() rndValue
GO

Declare @length int

Create Function dbo.randomint (@length int)
returns Varchar(50)
AS 
BEGIN
declare @positin int = 0
declare @numPool varchar = '1234567890'
declare @returnNum varchar = ''
while @position <= @Length
Begin
set @returnNum = @returnNum + (select Substring(@numPool, convert(int, rndValue*10),1))
set @position = @position + 1
end
return @returnNum
end