Ad

How To Do An Inline If-then In SQL Statement Syntax

I am trying to append my email to my @email string a bad @status is passed in. It works without the line I commented out. I think I'm close, but the syntax is wrong. @override_email is null.

DECLARE @retval INT
DECLARE @email nvarchar(200)
DECLARE @override_email nvarchar(200) = null
DECLARE @status INT = 2
DECLARE @in_customer_id INT = 160308

SET @email = COALESCE(@override_email, (
                      SELECT
                        COALESCE(CustomerDetail.Email, '')
                        /*+ (if @status NOT IN (3,4,5) ', [email protected]')*/
                      FROM
                        tbl_customer_detail     CustomerDetail
                      WHERE
                        CustomerDetail.customer_id = @in_customer_id))                      
select @email
Ad

Answer

You can do this using a CASE expression:

DECLARE @retval INT
DECLARE @email nvarchar(200)
DECLARE @override_email nvarchar(200) = null
DECLARE @status INT = 2
DECLARE @in_customer_id INT = 160308

SET @email = COALESCE(@override_email, (
                      SELECT
                        COALESCE(CustomerDetail.Email, '')
                        + case when @status NOT IN (3,4,5) then ', [email protected]' else '' end
                      FROM
                        tbl_customer_detail     CustomerDetail
                      WHERE
                        CustomerDetail.customer_id = @in_customer_id))                      
select @email
Ad
source: stackoverflow.com
Ad