SQL Server中Varchar(50)列与Int列相乘报错求助
解决SQL Server中Price_Each与Quantity_Ordered相乘的问题
错误原因
你遇到的转换错误,是因为Price_Each列的字符串包含美元符号$(甚至可能带空格),且值是小数格式,直接转换为int类型必然失败,同时价格本身应该用小数类型存储计算,而非整数。
临时查询计算(不修改表结构)
使用以下语句直接计算出total sales per person列:
SELECT Order_ID, Product, Quantity_Ordered, Price_Each, -- 先移除美元符号和左侧空格,再转为小数后相乘 CAST(LTRIM(REPLACE(Price_Each, '$', '')) AS DECIMAL(10,2)) * Quantity_Ordered AS [total sales per person] FROM DATA
LTRIM(REPLACE(Price_Each, '$', '')):清理字符串中的美元符号和左侧可能存在的空格,得到纯数字文本CAST(...) AS DECIMAL(10,2):将清理后的文本转换为支持小数的DECIMAL类型(10位总长度、2位小数,适配常规价格精度)- 最终与
int类型的Quantity_Ordered相乘,得到正确的销售总额
永久添加列到表中
如果需要将total sales per person作为永久列存在表中,执行以下两步:
- 添加列:
ALTER TABLE DATA ADD [total sales per person] DECIMAL(10,2);
- 更新列值:
UPDATE DATA SET [total sales per person] = CAST(LTRIM(REPLACE(Price_Each, '$', '')) AS DECIMAL(10,2)) * Quantity_Ordered;
内容的提问来源于stack exchange,提问作者user19859618
相关产品推荐
相关产品推荐

