You are subscribed to this thread Conditional Having Statement

Discussion in 'Databases' started by tiptap, Sep 2, 2009.

  1. #1
    Hey Guys,

    I have a huge statement loads of if statements in... and its getting bigger.

    On closer inspection there is only 3 difference in the select statement. so I thought I could cut the whole thing down to just 1 select statement if I have a conditional Having.

    I've simplified the IF statement down a bit to give you an idea of what im trying to achieve

    
    IF @month <> 0 & @diffFuture = 0 & @showDate <> 0
    	
    	HAVING (events.eventID = @eventID) 
    	AND 	(events.enabled = 1)
    	AND 	(MONTH(tickets_1.ticketStartDate) = MONTH(GETDATE())) 
    	AND	(YEAR(tickets_1.ticketStartDate) = YEAR(GETDATE()))
    
    IF @month <> 0 & @diffFuture <> 0 & @showDate <> 0
    
    	HAVING (events.eventID = @eventID) 
    	AND 	(events.enabled = 1)
    	AND 	(DATEPART(MONTH,tickets_1.ticketStartDate) = MONTH(@start)) 
    	AND 	(DATEPART(YEAR,tickets_1.ticketStartDate) = YEAR(@start))
    
    ELSE							
    	
    	HAVING (events.eventID = @eventID) 
    	AND 	(events.enabled = 1)		
    	AND 	(DATEPART(MONTH,tickets_1.ticketStartDate) = @month) 
    	AND	(DATEPART(YEAR,tickets_1.ticketStartDate) = @year)
    
    Code (markup):
    But how would i turn that into a conditional HAVING.... I thought the below would work

            HAVING (events.eventID = @eventID) 
    	AND 	(events.enabled = 1)	
            CASE
    	         WHEN @month <> 0 & @diffFuture = 0 & @showDate <> 0 THEN
                      	    (MONTH(tickets_1.ticketStartDate) = MONTH(GETDATE())) 
    	                    AND	(YEAR(tickets_1.ticketStartDate) = YEAR(GETDATE()))
                    WHEN...
            END
    Code (markup):
    Any ideas?
     
    tiptap, Sep 2, 2009 IP