Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Replace last two characters in column

Tags:

sql

I have a column with dates in the format 201201, 201202, 201203 etc.

This is a financial database so there is a period 13; however periods 12 & 13 are combined for reporting purposes.

When the last two characters are 13, how do I replace them with 12?

I started off with

SELECT REPLACE(PERIOD, '13', '12')
FROM @b_s_summary

but, of course this messes with the year when it's 2013.

All advice gratefully received.

like image 272
Tim Richards Avatar asked Oct 20 '25 14:10

Tim Richards


2 Answers

You can use Substring in this case:

SELECT REPLACE(PERIOD, SUBSTRING(PERIOD, len(PERIOD) - 1, 2), '12')
FROM @b_s_summary WHERE PERIOD LIKE '%13'

Does that fit you, or do you need a more dynamic approach for past or upcoming years?

like image 167
Fabian Bigler Avatar answered Oct 23 '25 04:10

Fabian Bigler


declare @Periods as Table ( Period VarChar(6) )
insert into @Periods ( Period ) values
  ( '201212' ), ( '201213' ), ( '201312' ), ( '201313' ) 

select Period, case
  when Right( Period, 2 ) = '13' then Substring( Period, 1, 4 ) + '12'
  else Period end as [AdjustedPeriod]
  from @Period
like image 28
HABO Avatar answered Oct 23 '25 03:10

HABO



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!