Link to home
Start Free TrialLog in
Avatar of VitaminD
VitaminDFlag for United States of America

asked on

Time Function Issue

I currently have a column in my fact table which is an int in the format of 20130701 for example

I need to be able to subtract 30 days from this date or whatever the date is

what is the best way to achieve this since I cannot change the datatype from Int to Datetime


Thanks in Advance
ASKER CERTIFIED SOLUTION
Avatar of Kyle Abrahams, PMP
Kyle Abrahams, PMP
Flag of United States of America image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Assuming this needs to be returned back to an integer, this would work (complete with demonstration from a temp table):

DECLARE @Table TABLE (
    seq     smallint    NOT NULL IDENTITY(1, 1),
    intdate int         NOT NULL )

INSERT INTO @Table (intdate)
SELECT  20130701 UNION ALL
SELECT  20130515

SELECT  *,
        CONVERT(int, CONVERT(varchar(10), CONVERT(datetime, CONVERT(varchar(8), intdate)) - 30, 112))
            AS NewIntDate
FROM    @Table

Open in new window

'fact table' indicates warehouse and likely data volume, plus use of integer also suggests desire for efficiency, so I'd caution you to avoid changing the data to suit your queries so that you preserve the advantages of indexes.

e.g.
DECLARE @from int, @until int
SET @from  = 20130601
SET @until = CONVERT(int, CONVERT(varchar,getdate(),112) )

;WITH
sample AS (
            SELECT 20140101 AS theInt UNION ALL
            SELECT 20130701 AS theInt UNION ALL
            SELECT 20130630 AS theInt UNION ALL
            SELECT 20130629 AS theInt
          )

SELECT
theInt, @from, @until
FROM sample
WHERE theInt >= CONVERT(int, CONVERT(varchar,dateadd(d, -30, CONVERT(varchar,@from,112) ) ,112) )
  AND theInt  < @until
;

Open in new window