Assuming that we are trying to alter the type of a column in a SQL table, say from varchar
to float
, using: ALTER TABLE <mytable. ALTER COLUMN <mycolumn> FLOAT
. However, we get the error Error to convert datatype varchar to float
.
Is it possible to narrow down the cells in the column that are causing this problem?
Thanks,
You can use the
ISNUMERIC
function:If you allow NULL values in your column, you'll also need to add a check for NULLs since
ISNUMERIC(NULL)
evaluates to 0 as wellDirty, but effective. This removes all characters found in floats (#s and decimal - I'm US-centric). The result you get from the query are items that would need to be reviewed to determine what should be done (ie the cells causing you problems).
Select any records where the
varchar
value contains any non-numeric charactersand any rows that might have more than one period:
I have encounter the same issue while writing ETL procedure. moving staging data into actual core table and we had all columns on staging table a NVARCHAR. there could be a numeric value which is either scientific format (like very large float values in Excel cell) or it has one of this special CHAR in it. ISNUMERIC function evaluates this char as True when it is appear as whole value. for example
so just check if any of cell in that column has such values.
if you find that cell has one of above then just exclude such data in your query. if you find that you have data in scientific format like "1.2408E+12" then ISNUMERIC will be still evaluate it as TRUE but straight insert will fail so convert in appropriate numeric format.