Converting varchar to decimal baseball average

前端 未结 2 2006
闹比i
闹比i 2021-01-23 12:45

I uploaded a CSV which automatically converted all my columns to varchar. I need to convert the value 22.30 to 0.223.

alter table badv2018
    alter column [BB          


        
2条回答
  •  抹茶落季
    2021-01-23 13:23

    I need to convert the value 22.30 to 0.223.

    You need to devide it by 100.0, then DECIMAL(4, 3) will be OK

    DECLARE @Value DECIMAL(4, 3) = 22.3 / 100.0;
    
    SELECT @Value
    

    Returns:

    0.223
    

    So, you need to UPDATE your table first, then ALTER the [BB Percent] column.

    The easy way is:

    • Add new column DECIMAL(4, 3).
    • Move the data into it.
    • Drop the old column.
    • Rename the new one.

    --First step
    ALTER TABLE badv2018
    ADD New DECIMAL(4, 3);
    
    --Second step
    UPDATE badv2018
    SET New = [BB Percent] / 100.0;
    
    --Third step
    ALTER TABLE badv2018
    DROP COLUMN [BB Percent];
    
    --The last step
    EXEC sp_rename 'badv2018.New', 'BB Percent', 'COLUMN';
    

    Enjoy!

    Live Demo


    UPDATE:

    You can also add a computed column and leave the [BB Percent] column, this way will ensure you can get the real data and the computed one.

    ALTER TABLE badv2018
    ADD New AS CAST([BB Percent] / 100.0 AS DECIMAL(4, 3));
    

提交回复
热议问题