简体   繁体   English

如何通过添加另一个数字来更新具有数字的 varchar 列?

[英]How do I update a varchar column that has a number by adding another number?

I have a column that is varchar(80) and is storing dollar amounts (no $ sign).我有一列是 varchar(80) 并且存储美元金额(没有 $ 符号)。 I would like to update the value by adding another amount, eg the existing amount is 96.73 and I want to add 1.00 to make 97.73.我想通过添加另一个金额来更新该值,例如现有金额是 96.73,我想添加 1.00 以得到 97.73。

I have tried cast and convert without any luck.我试过演员表和转换没有任何运气。 I have tried:我试过了:

set CAVALUETEXT = convert(INT, CAVALUETEXT) + 1.00
set CAVALUETEXT = cast(cavaluetext as int) + 1.00

and get the same error:并得到相同的错误:

Conversion failed when converting the varchar value '96.73' to data type int.将 varchar 值“96.73”转换为数据类型 int 时转换失败。

I think I am using SQL Server 2008.我想我正在使用 SQL Server 2008。

You could cast to DECIMAL , do the arithmetic, and then cast back to VARCHAR :可以转换DECIMAL ,进行算术运算,然后转换回VARCHAR

UPDATE yourTable
SET CAVALUETEXT = CAST(
    CAST(CAVALUETEXT AS DECIMAL(19,2)) + 1.00 AS VARCHAR(21));

But the much better approach here would be to stop storing currency amounts, especially amounts on which you might need to do arithmetic, in a text columns.但这里更好的方法是停止在文本列中存储货币金额,尤其是您可能需要进行算术运算的金额。 Use a proper type for this like DECIMAL(19,2) .为此使用适当的类型,例如DECIMAL(19,2)

You can use CONVERT(float, [YOUR Varchar]) .您可以使用CONVERT(float, [YOUR Varchar]) For example CONVERT(float, '0.123') convert it to a float 0.123 .例如CONVERT(float, '0.123')将其转换为浮点数0.123 This only works on SQL Server.这仅适用于 SQL Server。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM