Question 1
I am working with a system where date is stored as integer (actual numeric(8,0)) and I have noticed that other systems also store date as int such as cisco in this thread. Example
20120101 -- 01 Jan 2012
Is there any advantage of keeping numeric date system and not using SQL Datetime?
Question 2
Now I am trying to loop through numeric date to find customers between two dates. If the start
and enddate
encompass two months, I get thousands of records instead of just 60. Example:
create table #temp1(day int,capacity int) /* just a temp table */
declare @start int
declare @end int
set @start=20111201
set @end = 20120131
while (@start <= @end)
Begin
insert into #temp1 /* I am storing things in #temp table so data looks pretty */
exec usp_GetDailyCap @date1= @start
set @start = @start + 1;
end
select * from #temp1
This pulls 8931 records instead of 60. Is there a better way to improve the logic above so I pull only valid dates? I tried IsDate and sub-queries but that did not quite work in an efficient way.
Best Answer
To answer your first question, I would recommend using the
DATETIME
data type within SQL Server. Not necessarily for performance reasons, but to leverage the RDBMS-specific functionality. For instance, you would have to re-invent a lot of logic just to do basic date math (thinkDATEDIFF()
,DATEADD()
,DATEPART()
and many other functions. They are obviously tailored to theDATETIME
data type and are easy to work with).As for your second question, you are running into the exact problem that the first question (and my answer) is geared towards. You are looking at 20111201 and 20120131 as dates, and your brain is telling you that should be a difference of 60 days. Well, you're looping through based off of the delta...which is:
20120131 - 20111201 = 8930
(with the inclusive loop it'll be 8931)In other words, your
WHILE
loop is executing 8931 times. This is happening because those are integer values and your loop will not jump from 20111231 straight to 20120101.You integers aren't going to take into account the cap of years and months (i.e. your Question 2 problem).