简体   繁体   中英

SQL Query Returns NULL as a Value

I am trying to force an employee number when email address doesn't exist (is null) for a user. Regardless what I do, I always get NULL for the employee number in the result set. How do I force the employees number?

I have tried CASE WHEN len(B.email) < 1 THEN '1234568' This doesn't work.

I have tried CASE WHEN C.EMPLOYEE = 1234568 /*(b/c employee exists)*/ THEN '1234568' This doesn't work either.

I have also tried NULLIF(B.email,'EMAIL') This doesn't work either.

SELECT 
    EMPLOYEE, DATE, [JOB CODE], HM_ACCT_UNIT,
    CASE  
       WHEN SUM(HOURS) < '10.0' 
          THEN LEFT(REPLACE(SUM(ROUND(HOURS, 2)), '.', ''), 3)  
       WHEN SUM(HOURS) >= '10.0' 
          THEN LEFT(REPLACE(SUM(ROUND(HOURS, 2)), '.', ''), 4) 
       ELSE LEFT(REPLACE(SUM(ROUND(HOURS, 2)), '.', ''), 3) 
    END AS HOURS
FROM
    (SELECT
         CASE
            WHEN B.emaill = 'xx@some.com' THEN '123456'
            WHEN B.email = 'xy@some.com' THEN '123457'
            WHEN B.email IS NULL THEN '123458'
            ELSE RIGHT('000000' + CONVERT(VARCHAR, C.EMPLOYEE), 6)
         END AS 'EMPLOYEE',
         REPLACE(CONVERT(VARCHAR(10), CAST(a.start AS date), 101), '/', '') 'DATE',
         '14' as 'JOB CODE',
         -- CONVERT(int, REPLACE(dur, '.0', ''), 4) / 60 AS HOURS,
         CONVERT(DECIMAL(10, 2), dur) / 60 AS HOURS,
         CASE
            WHEN A.project = 'SOMETHINGELSE' THEN '123'
            ELSE '12345' 
         END AS 'HM_ACCT_UNIT'
     FROM 
         [dbo].[project] A
     LEFT OUTER JOIN 
         [dbo].[user] B ON A.uid = B.uid
     LEFT OUTER JOIN 
         EMPLOYEE C ON RTRIM(LTRIM(C.EMAIL_ADDRESS)) = LTRIM(RTRIM(B.email))
     LEFT OUTER JOIN 
         GL D ON D.ACCT_UNIT = C.HM_ACCT_UNIT
     LEFT OUTER JOIN 
         [dbo].[projList] CPT ON LTRIM(RTRIM(CPT.[Capital Project])) = LTRIM(RTRIM(A.project))
     WHERE 
         CONVERT(CHAR(10), a.start, 103) >= DATEADD(DAY, -14, GETDATE())
         AND (A.project LIKE '%SOMETHING%' OR A.project = 'SOMETHINGELSE')) A
GROUP BY 
    EMPLOYEE, DATE, [JOB CODE], HM_ACCT_UNIT
ORDER BY 
    DATE

My result set always returns this for one employee whose email is missing.

NULL    04072020    14  10XX202XX   5000

You can find out if the value is NULL using IS NULL . For example:

CASE WHEN B.email is null THEN '1234568'

You can combine this predicate with other ones using OR to cover other similar cases. For example:

CASE WHEN len(B.email) < 1 or B.email is null THEN '1234568'

I was overthinking this issue. The B.email was never null. I was mapping the B.email with C.EMAIL_ADDRESS. The issue is that the C.EMAIL_ADDRESS was null. I cant mark question as closed.

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