2

I have a column that has a month name in it as well as other text after the name of a specific month. What i want to do is extract the Months from that column and create a new column named Month.

|Ops/SLA Month      |
|APRIL SLA Reporting|
|APRIL OPS Reporting|

The column goes on and on with the months from april to march which would mean i cant use a substring since the months have different character lengths. Is there a way I can write a case statement or a query that will split this column into two columns? The intended results are as follows:

|Months |OPS/SLA      |
|April  |SLA Reporting|
|April  |OPS Reporting|

3 Answers3

3

You can try a query like below

create table tbl ([Ops/SLA Month] varchar(max));
insert into tbl values
('APRIL SLA Reporting')
,('APRIL OPS Reporting');

select 
    month = m.month,
    [OPS/SLA]= substring(t.[Ops/SLA Month],LEN(m.month)+1,8000)  
from tbl t cross join 
    (values
         ('January'),('February'),('March'),
         ('April'),('may'),('june'),
         ('july'),('August'),('September'),
         ('October'),('November'),('December'))m(month)
where t.[Ops/SLA Month] like m.month +'%'

working demo

DhruvJoshi
  • 17,041
  • 6
  • 41
  • 60
0

Try this

insert into <table_name1>
select 
    case when CHARINDEX(' ',[Ops/SLA Month])>0 
         then SUBSTRING([Ops/SLA Month],1,CHARINDEX(' ',[Ops/SLA Month])-1) 
         else [Ops/SLA Month] end Month, 
    CASE WHEN CHARINDEX(' ',[Ops/SLA Month])>0 
         THEN SUBSTRING([Ops/SLA Month],CHARINDEX(' ',[Ops/SLA Month])+1,len([Ops/SLA Month]))  
         ELSE NULL END as OPS/SLA
from <table_name2>;

Replace the table_name1,table_name2 with your fields.

Suvethan Nantha
  • 2,404
  • 16
  • 28
0

Assuming the first word (until first space) is always the month, the follwing should work:

SELECT
    CASE 
        WHEN CHARINDEX(' ', [OPS/SLA Month]) = 0 THEN NULL
        ELSE SUBSTRING([OPS/SLA Month], 1, CHARINDEX(' ', [OPS/SLA Month]) - 1)
        END AS [Months],
    CASE 
        WHEN CHARINDEX(' ', [OPS/SLA Month]) = 0 THEN [OPS/SLA Month]
        ELSE SUBSTRING([OPS/SLA Month], CHARINDEX(' ', [OPS/SLA Month]) + 1, 8000)
        END AS [OPS/SLA]
FROM myTable
MatSnow
  • 7,357
  • 3
  • 19
  • 31