patternsqlMinor
Why do subsequent unmet conditions in my CASE statement affect my return data type?
Viewed 0 times
casewhysubsequentstatementreturnaffecttypeconditionsdataunmet
Problem
I have the following variables and CASE statement:
There's nothing special about it. It returns 8 (int) as I expect it to.
However, as soon as I add to my CASE statement a conditional that returns a datetime data type, I no longer get 8 (int), despite continuing to use "I" as the @CONVERT_CODE value.
Instead, I get the datetime value of "1900-01-09 00:00:00.000"
I would think "D" shouldn't get evaluated at all because, in SQL Server, once a condition evaluates to true ("I" in this case), it should break out of the CASE statement--so I'm not sure why "D"s data type is affecting the overall return data type. Also, it doesn't matter if I reverse the order of the conditions and still use "I":
Am I missing something?
DECLARE @DATE_VALUE VARCHAR(20) = '4/29/2021'
DECLARE @CONVERT_CODE VARCHAR(1) = 'I'
SELECT CASE @CONVERT_CODE WHEN 'I' THEN DATEDIFF(day, '04/21/2021', @DATE_VALUE)
END AS ConvertedValueThere's nothing special about it. It returns 8 (int) as I expect it to.
However, as soon as I add to my CASE statement a conditional that returns a datetime data type, I no longer get 8 (int), despite continuing to use "I" as the @CONVERT_CODE value.
DECLARE @DATE_VALUE VARCHAR(20) = '4/29/2021'
DECLARE @CONVERT_CODE VARCHAR(1) = 'I'
SELECT CASE @CONVERT_CODE WHEN 'I' THEN DATEDIFF(day, '04/21/2021', @DATE_VALUE)
WHEN 'D' THEN GETDATE()
END AS ConvertedValueInstead, I get the datetime value of "1900-01-09 00:00:00.000"
I would think "D" shouldn't get evaluated at all because, in SQL Server, once a condition evaluates to true ("I" in this case), it should break out of the CASE statement--so I'm not sure why "D"s data type is affecting the overall return data type. Also, it doesn't matter if I reverse the order of the conditions and still use "I":
DECLARE @DATE_VALUE VARCHAR(20) = '4/29/2021'
DECLARE @CONVERT_CODE VARCHAR(1) = 'I'
SELECT CASE @CONVERT_CODE WHEN 'D' THEN GETDATE()
WHEN 'I' THEN DATEDIFF(day, '04/21/2021', @DATE_VALUE)
END AS ConvertedValueAm I missing something?
Solution
The column defined by your
SQL Server determines the resulting type in its usual way, making use of data type precedence. The type
You might be expecting the
CASE expression has a data type, as all columns do.SQL Server determines the resulting type in its usual way, making use of data type precedence. The type
datetime has a higher precedence than integer.You might be expecting the
CASE expression to return different types on different paths, but that is not possible (sql_variant aside).Context
StackExchange Database Administrators Q#290728, answer score: 6
Revisions (0)
No revisions yet.