Search code examples
sqlsql-servert-sqlcoalescenull-check

How to check sql database table field null or 0 and if so replace it with other column


I have a SQL query; I want to check two columns in query to check if they are null or 0; if so, then I want to replace then with other column's values.

Here is my query: I have used coalesce to check if it is null but how can I check for 0 and also how can I replace the columns with other values?

SELECT 
    t.Name
    ,t.Code
    ,c.Description
    ,st.APriceOld
    ,st.CPriceOld
    ,st.APriceNew
    ,st.CPriceNew
    COALESCE(st.APriceOld,st.APriceNew),
    COALESCE(st.CPriceOld,st.CPriceNew) 
FROM
    Table t
INNER JOIN
    STCP st ON st.PriceId = t.PriceId

Can anybody help me to get the expected result?

So if old price values are 0 or null, then they should be replaced with new price values


Solution

  • One more approach - use nullif() function:

    SELECT 
        t.Name
        ,t.Code
        ,c.Description
        ,st.APriceOld
        ,st.CPriceOld
        ,st.APriceNew
        ,st.CPriceNew
        COALESCE(NULLIF(st.APriceOld, 0), st.APriceNew),
        COALESCE(NULLIF(st.CPriceOld, 0), st.CPriceNew) 
    FROM
        Table t
    INNER JOIN
        STCP st ON st.PriceId = t.PriceId