2

我試圖將我的電子郵件附加到我的@email字符串中,但傳遞了錯誤的@status。它在沒有我註釋掉的行的情況下工作。我認爲我很接近,但語法錯誤。 @override_email爲空。如何在SQL語句語法中執行內聯if-then

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 

回答

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 ', [email protected]' else '' end 
         FROM 
         tbl_customer_detail  CustomerDetail 
         WHERE 
         CustomerDetail.customer_id = @in_customer_id))      
select @email 
+0

我發誓,我試過情況。我不認爲我把'然後',這一定是我的問題。一直讓我發瘋。這讓我等了4分鐘才接受這個答案...... –

+0

我也有過這些日子。此外,它看起來像你可能會添加一個逗號,如果沒有'@ override_email'或任何'CustomerDetail.Email',你可能不會想要。 –

+0

我使用[CDO](http://support.microsoft.com/kb/312839)發送電子郵件,它似乎處理流浪','沒有問題。儘管我做了測試,如果發生這種情況,我會遇到更大的問題。 –