How to set display to 0 if database storage is Null

CREATE PROCEDURE dbo.sp_pbos001_list AS

SELECT t1.id
    , t1.customer_code AS cus_code
    , (
        SELECT SUM(transaction_amt - cleared_amt)
        FROM pbosdeposit
        WHERE customer_code = t1.customer_code
        ) AS total_deposit
    , (
        SELECT SUM(inv_amt)
        FROM pbosinvoice
        WHERE customer_code = t1.customer_code
        ) - (
        SELECT SUM(cleared_amt)
        FROM pbosdeposit
        WHERE customer_code = t1.customer_code
        ) AS total_outstanding
FROM customer t1

For the total deposit and the total volume, I want it to display "0" on the display if the database is NULL.
I am trying to use if else but it does not work.

if(total_deposit = 'NULL')
set 0;
+4
source share
3 answers

Using coalesce:

            CREATE PROCEDURE dbo.sp_pbos001_list AS

            SELECT t1.id
                , t1.customer_code AS cus_code
                , coalesce((
                    SELECT SUM(transaction_amt - cleared_amt)
                    FROM pbosdeposit
                    WHERE customer_code = t1.customer_code
                    ),0) AS total_deposit
                , coalesce(((
                    SELECT SUM(inv_amt)
                    FROM pbosinvoice
                    WHERE customer_code = t1.customer_code
                    ) - (
                    SELECT SUM(cleared_amt)
                    FROM pbosdeposit
                    WHERE customer_code = t1.customer_code
                    )),0), AS total_outstanding
            FROM customer t1
+1
source

You can use COALESCEto replace NULL values:

SELECT t1.id
    , t1.customer_code AS cus_code
    ,COALESCE((
        SELECT SUM(transaction_amt - cleared_amt)
        FROM pbosdeposit
        WHERE customer_code = t1.customer_code
        ),0) AS total_deposit
    , COALESCE((
        SELECT SUM(inv_amt)
        FROM pbosinvoice
        WHERE customer_code = t1.customer_code
        ) - (
        SELECT SUM(cleared_amt)
        FROM pbosdeposit
        WHERE customer_code = t1.customer_code
        ),0) AS total_outstanding
FROM customer t1
+2
source

SQL Server:

ISNULL(total_deposit, 0)

MySql:

IFNULL(total_deposit, 0)
0
source

Source: https://habr.com/ru/post/1663597/


All Articles