如何将VARCHAR列转换为NUMBER?

时间:2019-11-09 21:27:23

标签: sql oracle

我正在尝试将整列(捐赠)转换为数字,而这是Oracle数据库中的varchar。当我使用TO_NUMBER函数时,会丢失右括号和无效的数字错误。

我尝试了to_number函数无济于事。

    insert into DD (Donor_ID, Donation_ID, Donation_Type, Donation, Inventory_ID) values 
   (1, 1, 'Food', 'Oranges', 1);
   insert into DD (Donor_ID, Donation_ID, Donation_Type, Donation, Inventory_ID) values 
   (2, 2, 'Currency', 200, 2);
   insert into DD (Donor_ID, Donation_ID, Donation_Type, Donation, Inventory_ID) values 
   (3, 3, 'Currency', 300, 2);
   insert into DD (Donor_ID, Donation_ID, Donation_Type, Donation, Inventory_ID) values 
   (4, 4, 'Currency', 400, 2);
   insert into DD (Donor_ID, Donation_ID, Donation_Type, Donation, Inventory_ID) values 
   (5, 5, 'Currency', 500, 2);

select di.Donor_Name DI, 
    acz.Address_City ACZ, 
    dd.Donation_Type DD, 
    TO_NUMBER('500' from dd.Donation DD) 

from DI di, ACZ acz, DD dd  
where dd.Donation_Type = 'Currency' AND dd.Donation > 499 
order by Donor_Name

我想要的结果是显示捐款>499。应该只显示一行。

1 个答案:

答案 0 :(得分:0)

如果您的数据库支持to_number(),则语法为:

select di.Donor_Name DI, 
       acz.Address_City ACZ, 
       dd.Donation_Type as DD, 
       to_number(dd.Donation) 
from DI di join
     ACZ acz
     on ? join  -- MISSING JOIN CONDITION
     DD dd 
     on ?       -- MISSING JOIN CONDITION
where dd.Donation_Type = 'Currency' AND dd.Donation > 499 
order by Donor_Name;

您忽略了所有join条件。

在大多数数据库中,您可以通过使用正确的数据类型存储值来解决问题。您也可以cast()的值:

cast(dd.donation as numeric(15, 4))  -- or whatever