Sql 如何编写select inside case语句

Sql 如何编写select inside case语句,sql,stored-procedures,sql-server-2012,case-statement,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 I

我有一个存储过程,它在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  
在行案例中,当发票交付类型为“USPS”时,则其他“Y”结束为发票交付

如果电子邮件有效,我需要检查有效的电子邮件地址,显示Y,否则显示N

所以这行应该是:

如果发票\交付类型为“USPS”,则如果为空,则从dbo.Client中选择emailaddr,其中客户端\ ID=子字符串发票\ ID,1,6,'Y',N'

如何写出此查询?

您可以通过案例来完成此操作。我认为以下是你想要的逻辑:

(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)

我收到一个错误,nvarchar值“20111028995999”的转换溢出了一个int列。EmailAddr实际上是一个GUIDvalue@user3929962 . . . 我认为查询不需要emailaddr,假设isnull的目的是确定是否返回了任何行,而不是email字段中的NULL值。该错误似乎与此代码无关。我用您所做的更改更新了我的查询,但仍然收到相同的错误。原始查询工作正常。@user3929962。此代码段中的任何内容都无法将包含14个字符的字符串转换为整数。根据where子句的不同,可能是6个字符的,但不是14个字符的。added和emailaddr不为null,查询现在可以工作。谢谢你的帮助