Duk
Duk

Reputation: 927

split string in sql server 2008

In my table, I have Experience field like

Experience

Here I want to split into

How to split strings here. I search so many articles. I can't find the correct solution. Is there any way to do here?

Upvotes: 1

Views: 7278

Answers (4)

praveen
praveen

Reputation: 12291

Try this using Parsename function

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

Demo in SQLFiddle

Upvotes: 0

TechDo
TechDo

Reputation: 18659

Please try:

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

Upvotes: 0

Marimuthu Kandasamy
Marimuthu Kandasamy

Reputation: 516

Try with following Steps...

                            --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

Upvotes: 0

Mudassir Hasan
Mudassir Hasan

Reputation: 28771

Here is a working solution

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

For working on your column replace '0to0Years' with column name

    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>

Upvotes: 3

Related Questions