1

在我的表中,我有经验字段,例如

经验

  • 0到0年
  • 2到0年
  • 7到12岁

这里我想分成

  • 年份从 - 0
  • 年初至今- 0

如何在此处拆分字符串。我搜索了很多文章。我找不到正确的解决方案。这里有什么办法吗?

4

4 回答 4

3

这是一个有效的解决方案

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>
于 2013-04-16T05:51:19.373 回答
0

尝试以下步骤...

                            --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
于 2013-04-16T06:06:40.783 回答
0

尝试使用 Parsename函数

Select  parsename(replace(Experience,'to','.'),2) ,
        substring(parsename(replace(Experience,'to','.'),1),0,
        charindex('Y',parsename(replace(Experience,'to','.'),1))) 
from YourTable

SQLFiddle中的演示

于 2013-04-16T06:02:52.387 回答
0

请试试:

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
于 2013-04-16T06:09:33.093 回答