Sybase UDF难度

Sybase UDF difficulty

当我尝试 运行 Sybase ASE 15.7 上的以下函数时,它只会无限期地旋转。该功能的每个组件似乎都独立地按预期运行。这只是一种从字符串中去除所有非数字字符的机制。任何想法都表示赞赏。

create function dbo.mdsudf_just_digits(@str varchar(64))  
returns varchar(64)  
as  
begin  
    while patindex('%[^0-9]%', @str) > 0  
        set @str = stuff(@str, patindex('%[^0-9]%', @str), 1, '')  
    return @str  
end  

-- A typical invocation would be like so:

select dbo.mdsudf_just_digits('hello123there456')
```

在 Sybase (ASE) 中,空字符串 ('') 实际上转换为单个 space:

select '.'+''+'.'     -- period + empty string + period
go

 ---
 . .                  -- we get a space between the periods

所以在当前 stuff(@str, ..., 1, '') 中,您实际上是用单个 space 替换第一个非数字。这个 'new' space 然后在下一次通过循环时匹配非数字测试,此时 space 被替换为...另一个 space。这导致无限循环,不断用 space.

替换第一个非数字字符

您可以通过使用 NULL 作为 stuff() 调用的最后一个参数来解决这个问题,例如:

set @str = stuff(@str, patindex('%[^0-9]%', @str), 1, NULL)