T-SQL Deterministic INT Cast
-
27-03-2021 - |
Question
Given:
- SQL Server
- Table called
TEST_TABLE
- Column in
TEST_TABLE
calledTEST_FIELD
of typeVARCHAR(50) NOT NULL
- Row 1: 10YR3/6
- Row 2: 10YR3/2
- Query:
SELECT TEST_FIELD FROM TEST_TABLE WHERE ...
Question:
In my where condition I need to test for values in the last character of the string. I notice the same behavior doing the following in the Where clause.
RIGHT(TEST_FIELD,1) > 3
CAST(RIGHT(TEST_FIELD,1) AS INT) > 3
Are they behaving the same through some inferred cast in case 1? Is case 1 deterministic?
Thanks in advance.
Matt
Solution
A conversion is done when you check the value for instance:
DECLARE @t varchar(100)
SET @t = (SELECT 'ABCA2')
SELECT @t
IF RIGHT(@t, 2) > 10
SELECT 'Hi'
ELSE
SELECT 'Bye'
Will throw an error because SQL cannot convert A2 to an integer without throwing an error.
However if you replace @t
with:
SET @t = (SELECT 'ABC12')
The above code will work as a conversion is successful and a comparison can be made. The right function itself does not convert your value. MSDN states the return type of RIGHT()
explicitly:
Returns varchar when character_expression is a non-Unicode character data type.
Returns nvarchar when character_expression is a Unicode character data type.
To make it easier on yourself, eliminate the function RIGHT()
altogether, when a comparison is done with text for instance:
DECLARE @t varchar(100)
SET @t = (SELECT '1')
SELECT @t
IF @t < 10
SELECT 'Hi'
ELSE
SELECT 'Bye'
Notice I did not make a call to Right()
. The result of the above is the display of 1 and then of the text Hi.
OTHER TIPS
And Yes case 1 is deterministic - either successful implicit conversion from string to integer(end then comparison between two integers) or exception thrown.