1

I have this query

SELECT  
    LineId, [LineNumber], 
    TotalNeed, TotalMRC, TotalMIV, TotalIMIV,
    (TotalMRC - TotalMIV) as Shortage
FROM  
    (SELECT  
         LineId,[LineNumber],
         ROUND(SUM(Quantity), 3) AS TotalNeed,
         SPMS2.dbo.ReturnTotalMRCByLineId(LineId) AS TotalMRC, 
         SPMS2.dbo.ReturnTotalMIVByLineId(LineId) AS TotalMIV,
         SPMS2.dbo.ReturnTotalIMIVByLineId(LineId) AS TotalIMIV
     FROM  
         [SPMS2].[dbo].[ViewMTO]
     GROUP BY 
         lineid, [LineNumber]) a

And these are the results :

enter image description here

As you can see some of my columns value are null. How can I set it to 0 if the value of that is null?

2
  • Use COALESCE(). Commented Sep 3, 2016 at 17:25
  • 1
    @GordonLinoff which part of query i should use it dear friend ? Commented Sep 3, 2016 at 17:26

2 Answers 2

1

Here is a simple way:

  SELECT mto.LineId, mto.[LineNumber], round(sum(mto.Quantity), 3) as TotalNeed
         v.*, (v.TotalMRC - v.TotalMIV ) as Shortage
  FROM [SPMS2].[dbo].[ViewMTO] mto CROSS APPLY
       (VALUES (ISNULL(SPMS2.dbo.ReturnTotalMRCByLineId(mto.LineId), 0),
                ISNULL(SPMS2.dbo.ReturnTotalMIVByLineId(mto.LineId), 0),
                ISNULL(SPMS2.dbo.ReturnTotalIMIVByLineId(mto.LineId), 0)
               )
       ) v(TotalMRC, TotalMIV, TotalIMIV)
  GROUP BY mto.lineid, mto.[LineNumber];

Normally, I prefer COALESCE() to ISNULL() (because the former is standard). However, COALESCE() evaluates the first argument twice. So for an expensive operation (such as a user-defined function), ISNULL() is more efficient.

Sign up to request clarification or add additional context in comments.

Comments

1

You can use the coalesce to replace a null with a value:

SELECT  LineId,
        [LineNumber],
        TotalNeed,
        TotalMRC,
        TotalMIV,
        TotalIMIV,
        (TotalMRC - TotalMIV) as Shortage
  FROM  (
        SELECT  LineId,[LineNumber],
                round(sum(Quantity),3) as TotalNeed
                ,COALESCE(SPMS2.dbo.ReturnTotalMRCByLineId(LineId), 0) as TotalMRC
                ,COALESCE(SPMS2.dbo.ReturnTotalMIVByLineId(LineId), 0) as TotalMIV
                ,COALESCE(SPMS2.dbo.ReturnTotalIMIVByLineId(LineId), 0)  as TotalIMIV
          FROM  [SPMS2].[dbo].[ViewMTO]
          GROUP BY lineid,[LineNumber]
        ) a

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.