Blog Post

Behavior of numeric data types with ”

,

As we all know, there are various numeric data types, such as TINYINT, INT, SMALLINT, BIGINT, NUMERIC, DECIMAL, SMALLMONEY, MONEY and FLOAT.

I was working on a SSIS package, which had staging table with all varchar columns. The files were loaded into the staging table, gets validated for the data type, length etc. and the valid records were then moved to the final tables. Final table had the actual numeric data types.

The source file had empty string (”) for the columns with no values, including in the numeric columns. I’ve noticed a strange behavior of ” with numeric data types. Although for most of the numeric columns, ” was treated as 0. SQL Server was converting the ” to 0. But for few numeric columns, it was failing with error “Error converting data type varchar to numeric”.

It surprised me! I started digging and here what I found.

Except NUMERIC and DECIMAL data types, all other numeric data types mentioned above were treating the empty string (”) as 0. But these two data types – NUMERIC and DECIMAL were throwing the error.

I tried to find out the cause of this strange behavior, but no luck! May be did not used the right keywords while googling.

You can try it out yourself using the following query. Do let me know if you found any reference proving the cause of this strange behavior!

I fixed the error by using NULLIF function to treat empty string (”) as NULL.

DECLARE @TINYINTAS TINYINT=''
DECLARE @INTAS INT=''
DECLARE @SMALLINTAS SMALLINT=''
DECLARE @BIGINTAS BIGINT=''
DECLARE @SMALLMONEYAS SMALLMONEY=''
DECLARE @MONEYAS MONEY=''
DECLARE @FLOATAS FLOAT=''
DECLARE @NUMERICAS NUMERIC=''
DECLARE @DECIMALAS DECIMAL=''

.

Original post (opens in new tab)
View comments in original post (opens in new tab)

Rate

You rated this post out of 5. Change rating

Share

Share

Rate

You rated this post out of 5. Change rating