如何在SQL语句语法中执行内联if-then

时间:2012-08-29 21:21:27

标签: sql sql-server-2008 tsql stored-procedures sql-server-2008-r2

我正在尝试将我的电子邮件附加到我的@email字符串中,传入了一个错误的@status。它没有我注释掉的行。我想我很接近,但语法错了。 @override_email为空。

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) ', alex@email.com')*/
                      FROM
                        tbl_customer_detail     CustomerDetail
                      WHERE
                        CustomerDetail.customer_id = @in_customer_id))                      
select @email

1 个答案:

答案 0 :(得分:2)

您可以使用CASE表达式执行此操作:

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 ', alex@email.com' else '' end
                      FROM
                        tbl_customer_detail     CustomerDetail
                      WHERE
                        CustomerDetail.customer_id = @in_customer_id))                      
select @email