Solved

If then in where clause

Posted on 2015-01-23
7
97 Views
Last Modified: 2015-02-01
I am trying to write a where clause if the month of today's date is = 1 then the date range is the beginning for the past year to the end of the past year, else it is the beginning of the current year to the end of last month.

Here is what I have now:

(dbo.OeOrders.OrderDateTime >= CAST(year(getdate())-1 as varchar(4))+'0101'  AND      dbo.OeOrders.OrderDateTime >= CAST(year(getdate()) as varchar(4))+'0101') 

Open in new window


Thanks

Glen
0
Comment
Question by:GPSPOW
  • 2
  • 2
  • 2
  • +1
7 Comments
 
LVL 65

Expert Comment

by:Jim Horn
ID: 40567256
So something like ...
WHERE 
  (SomeDate BETWEEN {beginning of last year} AND {end of last year} AND DATEPART(month, GETDATE()) = 1) OR 
  (SomeDate BETWEEN {beginning of currentyear} AND {end of last month} AND DATEPART(month, GETDATE()) <> 1)

Open in new window


btw if you had a Calendar Table in SQL Server, then you could join on the dates, do some math, and get all of the date boundaries you need, without having to use huge expressions.
0
 

Author Comment

by:GPSPOW
ID: 40567270
Unfortunately there is not a Calendar Table in the Sql Server.

I have always found that since the field data is formatted as datetime, the BETWEEN clause does not give me data after midnight on the end date.

Any suggestions?

Thanks

Glen
0
 
LVL 69

Expert Comment

by:ScottPletcher
ID: 40567295
Yeah, never use BETWEEN with date/datetime.

Don't use a calendar table unless you absolutely require it.  Wasted I/O mostly, but also some logic errors.


(dbo.OeOrders.OrderDateTime >= CASE WHEN month(getdate()) = 1
     THEN CAST(year(getdate())-1 as varchar(4))+'0101'
     ELSE dateadd(year, datediff(year, 0, getdate()), 0) END    
  AND      
  dbo.OeOrders.OrderDateTime < CASE WHEN month(getdate()) = 1
     THEN CAST(year(getdate()) as varchar(4))+'0101'
     ELSE dateadd(month, datediff(month, 0, getdate()), 0) END
0
Complete Microsoft Windows PC® & Mac Backup

Backup and recovery solutions to protect all your PCs & Mac– on-premises or in remote locations. Acronis backs up entire PC or Mac with patented reliable disk imaging technology and you will be able to restore workstations to a new, dissimilar hardware in minutes.

 
LVL 65

Expert Comment

by:Jim Horn
ID: 40567303
I've used Calendar tables with many clients with success, especially those that have custom business days that they need to track, or a fiscal calendar that doesn't have the same boundaries as a regular calendar.
0
 
LVL 69

Expert Comment

by:ScottPletcher
ID: 40567333
I've seen people use calendar tables to count the number of days in a month -- huge waste of resources.  Sometimes they get over-used for every calendar action, when they are actually only needed for a very small number of them.

I have a NonWorkDays table, not a full calendar table.  They're shorter, and by its very nature can't be used when it's not needed :-).
0
 
LVL 48

Accepted Solution

by:
PortletPaul earned 500 total points
ID: 40568617
Rather than a case expression containing an implied conversion of varchar to date, use dateadd() throughout:

WHERE (
      dbo.OeOrders.OrderDateTime >=
                  CASE WHEN MONTH(GETDATE()) = 1
                        THEN DATEADD(YEAR, DATEDIFF(YEAR, 0, GETDATE()) - 1, 0) -- Jan 1 last year
                        ELSE DATEADD(YEAR, DATEDIFF(YEAR, 0, GETDATE()), 0)
                  END
      AND dbo.OeOrders.OrderDateTime <
                  CASE WHEN MONTH(GETDATE()) = 1
                        THEN DATEADD(YEAR, DATEDIFF(YEAR, 0, GETDATE()), 0) -- Jan 1 this year
                        ELSE DATEADD(MONTH, DATEDIFF(MONTH, 0, GETDATE()), 0)
                  END
      )

Open in new window


test it with this:
declare @dt as datetime
set @dt = '20150117'

select
  CASE WHEN month(@dt) = 1 
     THEN dateadd(year, datediff(year, 0, @dt)-1, 0) -- Jan 1 last year
     ELSE dateadd(year, datediff(year, 0, @dt), 0) END     
  ,      
  CASE WHEN month(@dt) = 1 
     THEN dateadd(year, datediff(year, 0, @dt), 0) -- Jan 1 this year
     ELSE dateadd(month, datediff(month, 0, @dt), 0) END
;

declare @dt as datetime
set @dt = '20150324'

select
  CASE WHEN month(@dt) = 1 
     THEN dateadd(year, datediff(year, 0, @dt)-1, 0) -- Jan 1 last year
     ELSE dateadd(year, datediff(year, 0, @dt), 0) END     
  ,      
  CASE WHEN month(@dt) = 1 
     THEN dateadd(year, datediff(year, 0, @dt), 0) -- Jan 1 this year
     ELSE dateadd(month, datediff(month, 0, @dt), 0) END
;

Open in new window

0
 

Author Closing Comment

by:GPSPOW
ID: 40582642
Thanks

Worked very well.

Glen
0

Featured Post

What Security Threats Are You Missing?

Enhance your security with threat intelligence from the web. Get trending threat insights on hackers, exploits, and suspicious IP addresses delivered to your inbox with our free Cyber Daily.

Join & Write a Comment

Introduction In my previous article (http://www.experts-exchange.com/Microsoft/Development/MS-SQL-Server/SSIS/A_9150-Loading-XML-Using-SSIS.html) I showed you how the XML Source component can be used to load XML files into a SQL Server database, us…
Ever needed a SQL 2008 Database replicated/mirrored/log shipped on another server but you can't take the downtime inflicted by initial snapshot or disconnect while T-logs are restored or mirror applied? You can use SQL Server Initialize from Backup…
Using examples as well as descriptions, and references to Books Online, show the different Recovery Models available in SQL Server and explain, as well as show how full, differential and transaction log backups are performed
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.

708 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

18 Experts available now in Live!

Get 1:1 Help Now