Take the following SQL sample:
Declare @Table Table (Value int)
Insert Into @Table
Select intValueAsVarcharType
From OtherTable
Where Category = 'Type1'
The OtherTable.intValueAsVarcharType contains a list of nvarchar values, all the records for Category = Type1 are castable to ints. Values for other categories cannot all be casted to ints.
When we run the select (without the insert) we get a list of values that are all numeric ints, as expected.
When we run it with the insert we get the following error:
Conversion failed when converting the nvarchar value 'aaa' to data type int.
Another interesting thing is that if we change the where clause to the below:
Where Category = 'Type1'
and intValueAsVarcharType not like '%[^0-9]%'
The select statement returns the exact same result set, but this time the insert also works.
I can guess that this is likely caused by the way SQL optimises the query, and that it probably checks all that the values can be casted to int before it filters the result set.
What I'm not sure about is:
- Why exactly does adding the second where condition allow it to work when it doesn't change the result set? It seems to have the same execution plan as the statement without it.
- What is the best way to resolve this issue properly? Adding the second where clause seems to work but it feels "hacky" and I don't know if it will continue to work under all circumstances
TRY_CONVERT? -SELECT TRY_CONVERT(INT,@intValueAsVarcharType)– Scott Hodgin - Retired May 18 '18 at 09:24