ERROR USING CASEWITH DATES IN A SELECT STATEMENT
-
Thursday, February 28, 2013 12:17 AM
BEGIN
DECLARE @a SMALLINT;
SET @a = 1;
SELECT ABS= CASE
WHEN @a = 1 THEN YEAR(GETDATE())
WHEN @a = 2 THEN GETDATE()
ENDEND
Why do I get the following result:
ABS
----
1905-07-07 00:00:00.000When it Should be
ABS
----
2013But, if I comment the line "WHEN @a = 2 THEN GETDATE()", Then the execution result is OK.
All Replies
-
Thursday, February 28, 2013 12:22 AM
Try below.
BEGIN DECLARE @a SMALLINT; SET @a = 1; IF @a=1 SELECT YEAR(GETDATE()) ELSE SELECT GETDATE() END
ESHANI. Please click "Mark As Answer" if a post solves your problem or "Vote As Helpful" if a post has been useful to you
- Edited by Eshani Rao Thursday, February 28, 2013 12:35 AM
-
Thursday, February 28, 2013 12:24 AM
This is because the data type precedence specifies datetime is higher than INT... therefore what is happening is that the value 2013 is converted to DATETIME, as 1905-07-07 00:00:00.000..
SELECT CONVERT(datetime, 2013) returns the same value
Thanks! Josh Ash
- Edited by Josh Ashwood Thursday, February 28, 2013 12:25 AM
- Proposed As Answer by scott_morris-ga Thursday, February 28, 2013 1:45 PM
- Marked As Answer by Kalman TothMicrosoft Community Contributor, Moderator Thursday, March 07, 2013 1:22 AM

