Want to win a PS4? Go Premium and enter to win our High-Tech Treats giveaway. Enter to Win

x
Solved

# Time Function Issue

Posted on 2013-07-01
Medium Priority
214 Views
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

0
Question by:VitaminD
[X]
###### Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

• Help others & share knowledge
• Earn cash & points

LVL 41

Accepted Solution

Kyle Abrahams earned 2000 total points
ID: 39291688
declare @test int
set @test = 20130701

select dateadd(d, -30, cast(cast(@test as varchar(10)) as datetime))
0

LVL 20

Expert Comment

ID: 39291700
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
``````
0

LVL 49

Expert Comment

ID: 39292387
'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
;
``````
0

## Featured Post

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Why is this different from all of the other step by step guides?  Because I make a living as a DBA and not as a writer and I lived through this experience. Defining the name: When I talk to people they say different names on this subject stuff l…
Windocks is an independent port of Docker's open source to Windows.   This article introduces the use of SQL Server in containers, with integrated support of SQL Server database cloning.
Via a live example, show how to set up a backup for SQL Server using a Maintenance Plan and how to schedule the job into SQL Server Agent.
Via a live example, show how to shrink a transaction log file down to a reasonable size.
###### Suggested Courses
Course of the Month8 days, 5 hours left to enroll