Click here to Skip to main content
16,021,294 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Hi All,

Am facing one problem in sql query,
the Query is,

SELECT (CASE WHEN GETDATE()='2016-04-11' THEN (SELECT MONTH(GETDATE())) ELSE 12 END) as AvgSales

when i execute the above query it always displaying result 12
But MY expected output is,

if the date is current year then the result is MONTH(GETDATE())
if the date is previous year then the result is 12

So please help me out of this solution.

thanks in advance

What I have tried:

case statement in sql query not working
Posted
Updated 10-Apr-16 19:00pm

1 solution

GETDATE() will return current date with timestamp. CAST GETDATE() into DATE in the query.

SELECT (CASE WHEN CAST(GETDATE() AS DATE) ='2016-04-11' THEN (SELECT MONTH(GETDATE())) ELSE 12 END) as AvgSales
 
Share this answer
 
Comments
stellus 11-Apr-16 1:19am    
thanks Nitesh,
i tried your code but its showing the error like ,
"Type DATE is not a defined system type."
stellus 11-Apr-16 1:55am    
thanks nitesh,
i got the result instead of date i put datetime
NiteshAgarwal 11-Apr-16 3:15am    
Which SQL Server you are using? Data type date was introduced in SQL Server 2008.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900