2014-09-10 81 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