将 varchar 转换为十进制棒球平均值 [英] Converting varchar to decimal baseball average

查看:39
本文介绍了将 varchar 转换为十进制棒球平均值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我上传了一个 CSV,它会自动将我的所有列转换为 varchar.我需要将值 22.30 转换为 0.223.

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 Percent] decimal(4, 3) 

但我收到错误:

消息 8115,级别 16,状态 8,第 146 行
将数字转换为数字数据类型时出现算术溢出错误.

Msg 8115, Level 16, State 8, Line 146
Arithmetic overflow error converting numeric to data type numeric.

推荐答案

我需要将值 22.30 转换为 0.223.

I need to convert the value 22.30 to 0.223.

你需要除以100.0,然后DECIMAL(4, 3)就可以了

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

退货:

0.223

因此,您需要先UPDATE您的表,然后ALTER[BB Percent] 列.

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

简单的方法是:

  • 添加新列 DECIMAL(4, 3).
  • 将数据移入其中.
  • 删除旧列.
  • 重命名新的.
--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';

享受吧!

现场演示

更新:

您也可以添加一个计算列并保留[BB Percent]列,这样可以确保您获得真实数据和计算出的数据.

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));

这篇关于将 varchar 转换为十进制棒球平均值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆