2014-09-10 85 views
2

我有一個存儲過程,它包含一個select語句內的case語句。如何編寫一個select case case語句

select Invoice_ID, 'Unknown' as Invoice_Status, 
case when Invoice_Printed is null then '' else 'Y' end as Invoice_Printed, 
case when Invoice_DeliveryDate is null then '' else 'Y' end as Invoice_Delivered, 
case when Invoice_DeliveryType <> 'USPS' then '' else 'Y' end as Invoice_eDeliver, 
Invoice_ContactLName+', '+Invoice_ContactFName as ContactName, 
from dbo.Invoice 
left outer join dbo.fnInvoiceCurrentStatus() on Invoice_ID=CUST_InvoiceID 
where CUST_StatusID= 7 
order by Inv_Created 

在行case when Invoice_DeliveryType <> 'USPS' then '' else 'Y' end as Invoice_eDeliver

我需要檢查一個有效的電子郵件地址(如果電子郵件是有效的,顯示Y,否則顯示N)。

因此,行就應該是:

if Invoice_DeliveryType <> 'USPS' then '' else (If ISNULL(Select emailaddr from dbo.Client Where Client_ID = SUBSTRING(Invoice_ID, 1, 6)), 'Y', 'N')

我怎麼能寫出這樣的查詢?

回答

2

你可以用case做到這一點。我認爲以下是你想要的邏輯:

(case when Invoice_DeliveryType <> 'USPS' then '' 
     when exists (Select 1 
        from dbo.Client c 
        Where c.Client_ID = SUBSTRING(i.Invoice_ID, 1, 6) and 
         c.emailaddr is not null 
       ) 
     then 'Y' 
     else 'N' 
end) 
+0

我得到一個錯誤「轉換的nvarchar值'20111028995999'溢出了一個int列。 EmailAddr實際上是一個GUID值 – user3929962 2014-09-10 14:44:26

+0

@ user3929962。 。 。假設'isnull()'的目的是確定是否返回任何行,而不是電子郵件字段中的NULL值,我認爲查詢不需要'emailaddr'。該錯誤似乎與此代碼無關。 – 2014-09-10 14:56:53

+0

我更新了所做的更改,但仍然收到相同的錯誤。原始查詢完美地工作。 – user3929962 2014-09-10 15:01:13