Table1 有 两 列:
ID; Detail;
1; xxxxxName:Zhao+EDxxxxx
2; xxxName:Qian+EDxxxx
3; yyyName:Sun+EDxxxx
4;zzzzzName:Li+EDxxx
其中x,y,z都是未知长度的字符, 想把Name后面的名字(在Name 和 +ED 之间的字符串)取出来,然后更新表Table1 (增加一列Name),效果如下:
ID; Detail; Name
1; xxxxxName:Zhao+EDxxxxx; Zhao
2; xxxName:Qian+EDxxxx; Qian
3; yyyName:Sun+EDxxxx; Sun
4;zzzzzName:Li+EDxxx; Li
------解决思路----------------------
ALTER TABLE TB ADD Name VARCHAR(20)可以这样
UPDATE TB
SET Name=SUBSTRING(Detail,CHARINDEX('Name:',Detail)+5,CHARINDEX('+ED',Detail)-CHARINDEX('Name:',Detail,CHARINDEX('Name:',Detail))-5)
------解决思路----------------------
create table Table1
(ID int,Detail varchar(30))
insert into Table1
select '1','xxxxxName:Zhao+EDxxxxx' union all
select '2','xxxName:Qian+EDxxxx' union all
select '3','yyyName:Sun+EDxxxx' union all
select '4','zzzzzName:Li+EDxxx'
-- 增加一列Name
alter table Table1 add Name varchar(30)
update Table1 set Name=
substring(Detail,
charindex('Name:',Detail,1)+5,
charindex('+ED',Detail,1)-charindex('Name:',Detail,1)-5)
-- 结果
select * from Table1
/*
ID Detail Name
----------- ------------------------------ ------------------------------
1 xxxxxName:Zhao+EDxxxxx Zhao
2 xxxName:Qian+EDxxxx Qian
3 yyyName:Sun+EDxxxx Sun
4 zzzzzName:Li+EDxxx Li
(4 row(s) affected)
*/