如何在 sql 查询中将 SQL 列空值转换为 0 并将 varchar 转换为十进制

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

我需要将 varchar 数据类型中的 SQL 列转换为 decimal 并将空值转换为 0。这是我将 varchar 转换为decimal:

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

我需要将借方和贷方列的空值转换为零。如何在这段代码中插入空值转换部分?

使用 COALESCE 函数获取 NOT NULL 值。

试试这个:

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;

试试这个

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

改进了格式,对于 sql 服务器,有 isnull 选项......
查询应该是这样的

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
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