Table1 有 两 列:
ID; Detail;
1; xxx+xxName:Zhao+xxxxx
2; xxxName:Qian+xxxx+
3; +yyyName:Sun+xxxx
4;zzzzzName:Li+xxx
。。。
其中x,y,z都是未知长度的字符, 想把Name后面的名字(在Name 和 紧接着的 + 之间的字符串)取出来,但是注意+ 可能有好几个:
查询结果如下:
Zhao
Qian
Sun
Li
------解决思路----------------------
-- 好像昨天有这个问题
create table t(id int , detail varchar(30))
go
insert into t(id , detail)
select 1 , 'xxx+xxName:Zhao+xxxxx' union all
select 2 , 'xxxName:Qian+xxxx+' union all
select 3 , '+yyyName:Sun+xxxx' union all
select 4 , 'zzzzzName:Li+xxx'
go
with m as (
select id , SUBSTRING(detail,charindex(':',detail) + 1 ,30) detail from t
)
select id , SUBSTRING(detail ,0, charindex('+',detail)) from m
go
drop table t
go
(4 行受影响)
id
----------- ------------------------------
1 Zhao
2 Qian
3 Sun
4 Li
(4 行受影响)
------解决思路----------------------
SELECT已修改,取仅跟着Name的那个
SUBSTRING(
Detail
,CHARINDEX('Name:',Detail)+5
,CHARINDEX('+',Detail,CHARINDEX('Name:',Detail)+5)-CHARINDEX('Name:',Detail,CHARINDEX('Name:',Detail))-5)
FROM Table1
------解决思路----------------------
create table Table1
(ID int,Detail varchar(50))
insert into Table1
select 1,'xxx+xxName:Zhao+xxxxx' union all
select 2,'xxxName:Qian+xxxx+' union all
select 3,'+yyyName:Sun+xxxx' union all
select 4,'zzzzzName:Li+xxx'
select substring(Detail,
charindex('Name:',Detail,1)+5,
charindex('+x',Detail,charindex('Name:',Detail,1)+5)-charindex('Name:',Detail,1)-5
) 'Detail'
from Table1
/*
Detail
--------------------------------------------------
Zhao
Qian
Sun
Li
(4 row(s) affected)
*/