Skip to content Skip to sidebar Skip to footer

Sql Query To Split One Column Into Two Columns

I have one single column as project name, the data in project name 1.1.1 chapter1 1.1.2 chapter2 I want to divide that single column into two columns as Major Minor 1.1 .1

Solution 1:

Something like this

declare@x nvarchar(500) ='1.1.1 chapter1'selectsubstring(@x,1,charindex('.',@x,1+charindex('.',@x))-1) as Major,
       substring(@x,charindex('.',@x,1+charindex('.',@x)),len(@x)-charindex('.',@x,1+charindex('.',@x))) as Minor

Substitute @x in your query ..

and the fiddle for it : http://sqlfiddle.com/#!3/d41d8/4424/0

updated with the . in front and proof to error

declare @x nvarchar(500) = '1.1.1 chapter1'

select @x,
   casewhen charindex('.',@x,1+charindex('.',@x)) <> 0 then substring(@x,1,charindex('.',@x,1+charindex('.',@x))-1)
        else 'Cannot be parsed'
   end,
   case when charindex('.',@x,1+charindex('.',@x)) <> 0 then substring(@x,charindex('.',@x,1+charindex('.',@x)),len(@x)-charindex('.',@x,1+charindex('.',@x))+1)
        else 'Cannot be parsed'
   end

and without the . in front

declare @x nvarchar(500) = '1.1.1 chapter1'

select @x,
   casewhen charindex('.',@x,1+charindex('.',@x)) <> 0 then substring(@x,1,charindex('.',@x,1+charindex('.',@x))-1)
        else 'Cannot be parsed'
   end,
   case when charindex('.',@x,1+charindex('.',@x)) <> 0 then substring(@x,1+charindex('.',@x,1+charindex('.',@x)),len(@x)-charindex('.',@x,1+charindex('.',@x)))
        else 'Cannot be parsed'
   end

http://sqlfiddle.com/#!3/d41d8/4430/0

Solution 2:

selectsubstring(ProjectName,1,charindex('.',ProjectName,charindex('.',@t)+1)) asMajor

Post a Comment for "Sql Query To Split One Column Into Two Columns"