日期:2014-05-17  浏览次数:20476 次

请教 SQL Server2005中截取字符串问题?
请教 SQL Server2005中截取字符串问题?

有一个字段内容如下:

ASB-34A1-P033
AB-S2-D3
ABC-S32-D34
KJ-K4-ER-JK
H5-G323-FSS-G54
...

要求得到如下第二个'-'符号前面的数字如下:
1
2
32
4
323


------解决方案--------------------
SQL code

--写的太无聊了
create table tb(name varchar(20))
insert into tb 
select 'ASB-34A1-P033' union
select 'AB-S2-D3' union
select 'ABC-S32-D34' union
select 'H5-G323-FSS-G54' 


select REVERSE(left(REVERSE(left(RIGHT(name,len(name)-CHARINDEX('-',name)),
     CHARINDEX('-',RIGHT(name,len(name)-CHARINDEX('-',name)))-1)),
      PATINDEX('%[^0-9]%',REVERSE(left(RIGHT(name,len(name)-CHARINDEX('-',name)),
       CHARINDEX('-',RIGHT(name,len(name)-CHARINDEX('-',name)))-1)))-1))
from tb

/*

--------------------
32
2
1
323

------解决方案--------------------
SQL code
select substring(stuff(name,1,charindex('-',name),''),charindex('-',stuff(name,1,charindex('-',name),''))-1,1)
from tb
where len(name)-len(replace(name,'-','')) >= 2

------解决方案--------------------
探讨

引用:
SQL code
我仿照的代码如下:
select REVERSE(left(REVERSE(left(RIGHT(Bookcode,len(Bookcode)-CHARINDEX('-',Bookcode)),
CHARINDEX('-',RIGHT(Bookcode,len(Bookcode)-CHARINDEX('-',Bookcode)))-1)),
PATINDEX('%[^0-9]%',REVERSE(left(RIGHT(Bookcode,len(Bookcode)-CHARINDEX('-',Bookcode)),
CHARINDEX('-',RIGHT(Bookcode,len(mouldbarcode)-CHARINDEX('-',Bookcode)))-1)))-1))
from Book where createddate>='2011-8-1 00:00:00' and createddate<='2011-8-11 23:59:59'

但是执行时却出错如下:
消息 536,级别 16,状态 5,第 1 行
传递到 SUBSTRING 函数的长度参数无效。