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

怎样取一字符串中的数字型的字符?
表中有一列(xC)是字符型,

xC  
123P
34L
M230
H98G
...

怎样取得
xC
123
34
230
98
...

------解决方案--------------------

create function dbo.fn_DelCharacter
(@p varchar(8000))
returns varchar(8000)
as
begin
declare @i int
declare @ret varchar(8000)

set @ret= ' '
set @i=1

while @i <len(@p)
begin
if substring(@p,@i,1) in ( '0 ', '1 ', '2 ', '3 ', '4 ', '5 ', '6 ', '7 ', '8 ', '9 ')
set @ret=@ret + substring(@p,@i,1)
set @i=@i+1
end

return @ret

end
go


--创建测试表

create table T(f1 varchar(8000))


insert into T select 'xC '
insert into T select '123P '
insert into T select '34L '
insert into T select 'M230 '
insert into T select 'H98G '

select case when dbo.fn_DelCharacter (f1)= ' ' then f1 else dbo.fn_DelCharacter (f1) end
from T

go


drop function dbo.fn_DelCharacter
drop table T

------解决方案--------------------
create table tab(xc varchar(10))
insert tab
select '123P '
union all
select '34L '
union all
select 'M230 '
union all
select 'H98G '
--要求得到其中的数字部分

select patindex( '%[0-9]% ',xc),len(xc),len(xc)-patindex( '%[0-9]% ',xc),
right(xc,len(xc)-patindex( '%[0-9]% ',xc)+1),
patindex( '%[A-Z]% ',right(xc,len(xc)-patindex( '%[0-9]% ',xc)+1)),
substring(xc,patindex( '%[0-9]% ',xc),(case when patindex( '%[A-Z]% ',right(xc,len(xc)-patindex( '%[0-9]% ',xc)+1))=0 then len(right(xc,len(xc)-patindex( '%[0-9]% ',xc)+1)) else patindex( '%[A-Z]% ',right(xc,len(xc)-patindex( '%[0-9]% ',xc)+1))-1 end))
from tab
drop table tab
------解决方案--------------------
wangtiecheng 大大的方法好写.
gaojier1000 大大的方法有局限性.

如果有的数据 是 1A1 或者 1A1A1
这样有穿插的就不行了
------解决方案--------------------
--創建測試環境
Create Table TEST(xC Varchar(100))
--插入數據
Insert Into TEST Select '123P '
Union All Select '34L '
Union All Select 'M230 '
Union All Select 'H98G '
GO
--創建函數
Create Function F_GetNumeric(@xC Varchar(100))
Returns Varchar(100)
As
Begin
Declare @NewxC Varchar(100)
Select @NewxC = ' '
While(Len(@xC) > 0)
Begin
If (ASCII(Left(@xC, 1)) Between 48 And 57)
Select @NewxC = @NewxC + Left(@xC, 1)
Select @xC = Stuff(@xC, 1, 1, ' ')
End
Return @NewxC
End
GO
--測試
Select dbo.F_GetNumeric(xC) As xC From TEST
GO
--刪除測試環境
Drop Table TEST
Drop Function F_GetNumeric
--結果
/*
xC
123
34
230
98
*/