日期:2014-05-18  浏览次数:20531 次

怎样才能实现类似parseInt 样的函数
返回由字符串转换得到的整数.
如:
parseInt("abc") // 返回 0。
parseInt("12abc") // 返回 12

------解决方案--------------------
try:
DECLARE @s VARCHAR(100)
SET @s='12bbc'
SELECT @s,SUBSTRING(@s,1,PATINDEX ('%[a-z]%',LOWER(@s))-1)
------解决方案--------------------
SQL code
use test 
go
create function test_num(@s nvarchar(50))
returns  int
as
begin
declare @s1 nvarchar(10)
while patindex('%[0-9]%',@s)>0
select @s1=isnull(@s1,'')+substring(@s,patindex('%[0-9]%',@s),1),
@s=stuff(@s,1,patindex('%[0-9]%',@s),'')
return isnull(@s1,0)
end
go
select dbo.test_num('12abc'), dbo.test_num('abc')

           
----------- -----------
12      0

(所影响的行数为 1 行)