将不规则的 Varchar 转换为数字
Convert Irregular Varchar to Numeric
我有一个 table 超过 16,000 行描述了客户账单上的欠款。不幸的是,欠款金额以一种奇怪的方式设置 - 货币金额存储为 varchar,并且在到期时,减号位于数字右侧,如下所示:
Amount
36.30
21.48-
132.65-
87.91-
1.20
我在我的 table 中添加了一个名为 Amount_num
的新列,我想对我的 table 进行更新,这将给我以下内容:
Amount Amount_num
36.30 36.30
21.48- -21.48
132.65- -132.65
87.91- -87.91
1.20 1.20
我尝试了以下更新查询:
UPDATE [CHARGE_TABLE]
SET [Amount_num] = CAST ([Amount] as decimal (18,2))
这给了我 'Error converting data type varchar to numeric'。我应该改变什么?
这应该适用于您奇怪的字符串格式。
UPDATE [CHARGE_TABLE]
SET [Amount_num] = convert(numeric(18,2), Case when Amount like '%-' then '-' else '' end + REPLACE(Amount, '-', ''))
我有一个 table 超过 16,000 行描述了客户账单上的欠款。不幸的是,欠款金额以一种奇怪的方式设置 - 货币金额存储为 varchar,并且在到期时,减号位于数字右侧,如下所示:
Amount
36.30
21.48-
132.65-
87.91-
1.20
我在我的 table 中添加了一个名为 Amount_num
的新列,我想对我的 table 进行更新,这将给我以下内容:
Amount Amount_num
36.30 36.30
21.48- -21.48
132.65- -132.65
87.91- -87.91
1.20 1.20
我尝试了以下更新查询:
UPDATE [CHARGE_TABLE]
SET [Amount_num] = CAST ([Amount] as decimal (18,2))
这给了我 'Error converting data type varchar to numeric'。我应该改变什么?
这应该适用于您奇怪的字符串格式。
UPDATE [CHARGE_TABLE]
SET [Amount_num] = convert(numeric(18,2), Case when Amount like '%-' then '-' else '' end + REPLACE(Amount, '-', ''))