简体   繁体   中英

T-SQL concatenation issue with NULLS

I'm trying to do a simple concatenation but failing somewhere! I want to display the Note in the email only if the other two variables are not empty. Even if one variable contains data it should display the Note. Below is my code.

SET @Note = CASE 
               WHEN @tableHTML_AssignedTo IS NOT NULL OR @tableHTML_SubmittedBy IS NOT NULL
                  THEN 'Note: The tickets with the following statuses are not listed in this alert: Closed,Rejected' 
                  ELSE NULL
            END

SET @ComposeBody = ISNULL(@tableHTML_AssignedTo, '') +
                   ISNULL(@tableHTML_SubmittedBy, '') +
                   ISNULL(@Note, '') 

I know it's simple code but it's not obvious to my mind what I'm doing wrong. But with my code, an empty email is sent if both the tables are empty with Notes. If I remove Notes, no email is sent but I want to add the Notes in the email

Note: I'm executing this code inside cursor to send emails recursively

I'd do it like this -- seems simpler.

The trick here is to understand how null works with concat. Anything concat with null is null. So the first parameter to COALESCE will be null if Assigned or submitted is null. Each next step checks the other two cases.

SET @Note = 'Note: The tickets with the following statuses are not listed in this alert: Closed,Rejected'; 

SET @ComposeBody = COALESCE(
     @tableHTML_AssignedTo+@tableHTML_SubmittedBy+@Note,  -- Selected if both non null
     @tableHTML_AssignedTo+@Note,                         -- Selected if SubmittedBy null
     @tableHTML_SubmittedBy+@Note)                        -- Selected if AssignedTo null
                       -- Both are null, set body to null.

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