如何编写一个select内部case语句

时间:2014-09-10 14:25:53

标签: sql stored-procedures sql-server-2012 case-statement

我有一个存储过程,其中包含select语句中的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')

我该如何写出这个查询?

1 个答案:

答案 0 :(得分: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)