Yesterday I had a chat with one of my friend who was having problem with his SQL Query.
Ill just list down his Peculiar problem and the way we solved it in this blog post. It would be a good learning to all.

The problem he had:
– There was an insert script for a table(say it tablex).
– All the columns in this table were of type varchar(100).
This insert script was running fine for most of the insert values, but was failing when one of the column has value ‘123E99’.
– The error the script was giving was:

Msg 8114, Level 16, State 5, Line 1
Error converting data type varchar to bigint.

All the columns being varchar, why was this error occuring?
Why is this datatype conversion happening?
Is this conversion implicitly happening or it explicitly done?
Why was this error occuring only for value ‘123E99’ but not for value ‘128M99’?

Following are the steps we followed to find the reason for this error:
Checked the table definition to see if there were any triggers on the table.
There were no triggers on this table

Analysed the input value which was giving the error.
‘123E99’ – This value has E as part of it.
When the below query is executed it gives 1 as output.
SELECT isnumeric(‘123E99’);

But the output will be 0 for ‘128M99’.
This means sql server understands ‘123E99’ as a numeric value but not ‘128M99’.

So there is some part of code somewhere in the database which is causing this issue by validating weather the value is numeric.

So we went ahead and searched for all the indexed views in the database.
We found one that is using this table.

Below is the piece of code in this indexed view
CASE WHEN ISNUMERIC(tablex.column2) = 1
THEN CONVERT(BIGINT,tablex.column2)

So this is the code that is giving the above error.
The ISNUMERIC is giving true but conversion to big int is failing as the value is larger that that of bigint.
Modifying this piece of code solved the issue. 🙂

Why was this indexed view code running when he was executing the insert script on tablex?

Just Because tablex is being used in the indexed view, indexed view has to be indexed with new data in tablex

Learnings form this post:
When you face such peculiar issues of conversion etc..

  • check for the design of the table and see if the conversion is implicitly happening.
  • Check for the triggers on the table, and see if there is any implicit or explicit datatype conversion happening there.
  • Check for the indexed views in the database, See if there is any implicit or explicit datatype conversion in the indexed views.

Leave a Reply

Your email address will not be published. Required fields are marked *