SQL Converting Column type from float to varchar
You can fix this by going through a decimal
first:
ALTER TABLE Customer ALTER COLUMN Phonenumber decimal(25, 0);ALTER TABLE Customer ALTER COLUMN Phonenumber varchar(25);
You get the same behavior when using cast()
:
select cast(cast(1549779498 as float) as varchar(255))
So the fix is illustrated by:
select cast(cast(cast(1549779498 as float) as decimal(25)) as varchar(255))
The documentation for alter table alter column
explicitly references cast()
:
Some data type changes may cause a change in the data. For example, changing an nchar or nvarchar column to char or varchar may cause the conversion of extended characters. For more information, see CAST and CONVERT (Transact-SQL). Reducing the precision or scale of a column may cause data truncation.
EDIT:
After you load the data, I would suggest that you also add a check constraint:
check (PhoneNumber not like '%[^0-9]%')
This will ensure that numbers -- and only numbers -- remain in the column in the future.
Direct float to varchar conversions can be tricky. Merely altering column data type wont be sufficient.
STEP 1: Take backup of your data table.
SELECT * INTO Customer_Backup FROM Customer
STEP 2: Drop and Create your original data table using SQL Server Scripts // OR // DROP and Alter the data type of the column
ALTER TABLE Customer ALTER COLUMN Phonenumber varchar(25)
STEP 3: In you scenario, since phone numbers don't have decimal data values in the float column, we can convert it first to int and then to varchar like below
INSERT into Customer (Phonenumber) SELECT convert (varchar(25), convert(int, [Phonenumber])) as [Phonenumber]FROM Customer_Backup
ALTER TABLE Customer ADD PhonenumberVarchar VARCHAR(25)GOUPDATE Customer SET PhonenumberVarchar = str (Phonenumber,12,0)ALTER TABLE Phonenumber ALTER COLUMN Phonenumber VARCHAR(25)UPDATE Customer SET Phonenumber = PhonenumberVarchar ALTER TABLE Customer DROP COLUMN PhonenumberVarchar