1

I have a table with INT datatype column and my data is something like this

valid_to_day(int)
------------
20150301
20150101

I want to get previous date of this column, if I perform -1 to the above data the data is something like this

valid_to_day
------------
20150300
20150100

Expected data

valid_to_day
------------
20150228
20141231

Please can anyone help

Thanks in advance

satish

marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
  • 4
    Why are you storing your dates as integers, which will make handling this much more difficult? You should store your dates as...dates. – Tim Biegeleisen Sep 11 '16 at 12:40

3 Answers3

4

You shouldn't store dates like that.

The Date datatype is more compact, ensures you have no invalid dates, and can be used with date functions.

Hopefully you need this so you can fix your schema.

One method which does not rely on casting to string would be

SELECT DATEFROMPARTS(valid_to_day/10000, valid_to_day%10000/100, valid_to_day%100)

And of course now it is the proper datatype you can just use DATEADD to get the previous day.

SELECT DATEADD(DAY,
                -1, 
                DATEFROMPARTS(valid_to_day/10000, valid_to_day%10000/100, valid_to_day%100)
               ) 
Martin Smith
  • 438,706
  • 87
  • 741
  • 845
0

You can use dateadd function along with convert type of 112

declare @d int = 20150301

select  convert(int, convert(varchar(10), dateadd(d,-1,convert (date, convert(varchar(10),@d), 112)),112))
Kannan Kandasamy
  • 13,405
  • 3
  • 25
  • 38
0

Convert first INT to VARCHAR and then to DATE:

DECLARE @d INT = 20150101

SELECT CAST(CAST(@d AS VARCHAR(8)) AS DATE)
SELECT DATEADD(d,-1,CAST(CAST(@d AS VARCHAR(8)) AS DATE))
SELECT 
    REPLACE
    (
        CAST
        (
            DATEADD(d,-1,CAST
                        (
                            CAST(@d AS VARCHAR(8)) AS DATE)
                        ) 
            AS VARCHAR(10)
        )
        ,'-',''
    )