在我的表中,我有经验字段,例如
经验
- 0到0年
- 2到0年
- 7到12岁
这里我想分成
- 年份从 - 0
- 年初至今- 0
如何在此处拆分字符串。我搜索了很多文章。我找不到正确的解决方案。这里有什么办法吗?
在我的表中,我有经验字段,例如
经验
这里我想分成
如何在此处拆分字符串。我搜索了很多文章。我找不到正确的解决方案。这里有什么办法吗?
这是一个有效的解决方案
declare @yearfrom varchar(2),@yearto varchar(2)
select @yearfrom=substring('0to0Years',0,patindex('%to%','0to0Years')),
@yearto=substring('0to0Years',patindex('%to%','0to0Years')+2,patindex('%Years%','0to0Years')-patindex('%to%','0to0Years')-2)
SqlFiddle:http ://www.sqlfiddle.com/#!3/d41d8/12483
要处理您的列,请将“0to0Years”替换为列名
declare @yearfrom varchar(2),@yearto varchar(2)
select @yearfrom=substring(col_name,0,patindex('%to%',col_name)),
@yearto=substring(,patindex('%to%',col_name)+2,patindex('%Years%',col_name)-patindex('%to%',col_name)-2)
from table_name where <condition>
尝试以下步骤...
--Create Table :
Create Table #Table
(
Name Varchar(50),
Experience Varchar(20)
)
Go
-- Insert Values :
Insert into #Table Values('Tom','0to0Years')
Insert into #Table Values('Victor','0to1Years')
Insert into #Table Values('Mark','11to12Years')
Go
--View Data
Select * from #Table
--Using CharIndex and Substring :
Select Name,
Substring(Experience,1,CharIndex('to',Experience)-1) as Yearfrom,
Substring(Experience,(CharIndex('to',Experience)+2),Len(Replace(Experience,'Years','')) - (CharIndex('to',Experience)+1)) as YearTo
from #Table
请试试:
select 'YearFrom - '+substring(Data, 0, PatIndex('%[to]%', Data)) YearFrom,
'YearTo - '+replace(stuff(Data, 1, PatIndex('%[to]%', Data)+1, ''), 'Years', '') YearTo
from
(
Select '0to0Years' Data union
Select '2to0Years' Data union
Select '756to12Years' Data
)x