Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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
like image 968
Alex Kwitny Avatar asked Jan 22 '26 07:01

Alex Kwitny


1 Answers

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
like image 109
Tim Lehner Avatar answered Jan 23 '26 21:01

Tim Lehner



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!