I have a database with a column of VarChar type, within which are integers (which I want to keep) and miscellaneous non-numeric values (which I want to remove). If I alter the table and add a new integer column, how can I copy only the integers into the new integer column?
+5
A:
I'd give this a shot (will work with MSSQL, not sure about other database systems)...
update MyTable
set MyNewIntField = cast(MyOldVarcharField as int)
where isnumeric(MyOldVarcharField) = 1
Scott Ivey
2009-06-23 16:35:33
As long as you don't mind truncating the floats and including them, then this method works fine.
Chris Simpson
2009-06-23 16:39:42
+1
A:
this should do it for you if you are running MS SQL:
update mytable set new_column = old_column where isnumeric(old_column) = 1
Jason Heine
2009-06-23 16:36:58
A:
You will fail out if you end up trying to put decimal data into the integer column.
You have 2 choices here
you could only accept data if it is whole numbers:
update [table]
set [integer column] = [varchar column]
where isnumeric([varchar column])=1 and ([varchar column] not like '%.%')
or you could round or truncate the decimals
--truncate
update [table]
set [integer column] = floor(cast([varchar column] as float))
where isnumeric([varchar column])=1
--round
update [table]
set [integer column] = round(cast([varchar column] as float),0)
where isnumeric([varchar column])=1
Patrick Taylor
2009-06-23 21:26:34