当前位置: 代码迷 >> Sql Server >> 请问 SQL Server2005中截取字符串有关问题
  详细解决方案

请问 SQL Server2005中截取字符串有关问题

热度:88   发布时间:2016-04-27 11:22:16.0
请教 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' unionselect 'AB-S2-D3' unionselect 'ABC-S32-D34' unionselect '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/*--------------------3221323
------解决方案--------------------
SQL code
select substring(stuff(name,1,charindex('-',name),''),charindex('-',stuff(name,1,charindex('-',name),''))-1,1)from tbwhere 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 函数的长度参数无效。

  相关解决方案