简体   繁体   中英

How to convert SQL column null value to 0 and varchar to decimal in sql query

I need to convert a SQL column which is in varchar datatype to decimal and the null values to 0. This is my code to convert varchar to decimal :

SELECT 
    CAST(debit as DECIMAL(9,2)),
    CAST(credit as DECIMAL(9,2)),
    sum_accname,
    sum_date, 
    sum_description
FROM 
    sum_balance

I need to convert debit and credit column null values to zero. How to insert the null value converting part to this code?

SELECT 
    COALESCE(CAST(debit as DECIMAL(9,2)),0) as debit,
    COALESCE(CAST(credit as DECIMAL(9,2)),0) as credit,
    sum_accname,
    sum_date, 
    sum_description
FROM 
    sum_balance

Use COALESCE function to fetch NOT NULL values.

Try this:

SELECT 
    CAST(COALESCE(debit, '0') AS DECIMAL(9,2)),
    CAST(COALESCE(credit, '0') AS DECIMAL(9,2)),
    sum_accname,
    sum_date, 
    sum_description
FROM 
    sum_balance;

try this

SELECT 
    CAST(isnull(debit ,0) as DECIMAL(9,2)),
    CAST(isnull(credit,0) as DECIMAL(9,2)),
    sum_accname,
    sum_date, 
    sum_description
FROM 
    sum_balance

improved formatting,for sql server there is option for isnull.......
the query should be like this

SELECT isnull(CAST(debit as DECIMAL(9,2)),0), 
isnull(CAST(credit as DECIMAL(9,2)),0), sum_accname, sum_date, sum_description
FROM sum_balance

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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