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

求函数将字符串转为数字型
将一些金额转换为数字:
250.5     ->   250
200万     ->   200
12万(rmb)->   12
12.5元   ->   12

就是去除小数点后或是非数字字符。谢谢大家。本来想稍微改下过去找的过程的……
但好像没有吧小数点后面的数字也去掉。
CREATE   function   fn_num(
@str   varchar(60)
)
returns   varchar(60)
as
begin
      declare   @r   varchar(60)
      set   @r= ' '
      while   PATINDEX( '%[0-9]% ',@str)> 0
      begin
                set   @str=stuff(@str,1,PATINDEX( '%[0-9]% ',@str)-1, ' ')
                if   PATINDEX( '%[^0-9]% ',@str)> 0
                begin
                        set   @r=@r+left(@str,PATINDEX( '%[^0-9]% ',@str)-1)
                        set   @str=stuff(@str,1,PATINDEX( '%[^0-9]% ',@str)-1, ' ')
                end
                else  
                begin
                        set   @r=@r+@str
                        set   @str= ' '
                end
        end
      if   ISNUMERIC(@r)=0
      begin  
      set   @r   =   '0 '
      end
      return   @r
end

------解决方案--------------------
declare @a table(a varchar(100))
insert @a select '250.5 '
union all select '200万 '
union all select '12万(rmb) '
union all select '12.5元 '

select left(a, patindex( '%[^0-9]% ',a)-1) from @a where patindex( '%[^0-9]% ',a)> 0
------解决方案--------------------
--result
/*
-----------------
250
200
12
12

(所影响的行数为 4 行)
*/
------解决方案--------------------
create table tb(col varchar(20))
insert into tb values( '250.5 ')
insert into tb values( '200万 ')
insert into tb values( '12万 ')
insert into tb values( '12.5元 ')
go

create function getnewstr
(@oldstr varchar(100))
returns varchar(100)
as
begin
declare @i int
set @i = 1
while @i <= len(@oldstr)
if substring(@oldstr, @i, 1) like( '[^0-9] ')
set @oldstr = replace(@oldstr, substring(@oldstr, @i, 1), ' ')
else
set @i = @i +1
return @oldstr
end
go

update tb
set col = dbo.getnewstr(col)
where col like( '%[^0-9]% ')

select * from tb

drop table tb
drop function getnewstr
/*
col
--------------------
2505
200
12
125
(所影响的行数为 4 行)
*/
------