【问题标题】:Filtering stored procedure records by nested select case statement通过嵌套的 select case 语句过滤存储过程记录
【发布时间】:2014-09-14 20:10:17
【问题描述】:

我需要从 this post 进一步优化我的存储过程结果集,我需要过滤我的结果集以仅显示 emailaddr 为 NULL 的记录(意味着仅显示 Invoice_DeliveryType 值为 'N' 的记录)。

在众多查询中,我尝试过:

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 ''
          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)
    Invoice_ContactLName + ', ' + Invoice_ContactFName as ContactName, 
from 
    dbo.Invoice
left outer join 
    dbo.fnInvoiceCurrentStatus() on Invoice_ID = CUST_InvoiceID 
where 
    CUST_StatusID = 7 
    AND Invoice_ID = dbo.Client.Client_ID
    AND dbo.client.emailaddr is NULL
order by 
    Inv_Created  

但我得到一个错误

nvarchar 值 '20111028995999' 的转换溢出了一个 int 列

如何让存储过程只返回 DeliveryType = 'N' 的记录?

【问题讨论】:

  • Invoice_ID = dbo.Client.Client_IDdbo.client.emailaddr is NULL 谓词没有任何意义:在该级别的查询中没有 dbo.Client
  • 此外,查询中的某些列不符合表引用的条件并不能更好地理解问题。

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


【解决方案1】:

尝试将存储的过程结果选择到临时表中,然后选择 * 来自#TempTable

【讨论】:

【解决方案2】:

我们真的可以使用架构定义来解决这个问题。

似乎在您的一个案例语句中发生了隐式转换,但是如果没有架构定义,就很难找到是哪一个。

您不能安全地在 CASE 表达式中混合数据类型,除非您绝对确定任何隐式转换都能正常工作,否则您应该使转换显式。

从错误消息来看,似乎包含的内容可能是表示为字符串的日期(20111028)加上某种其他数据?时间?(995999)可能与Invoice_DeliveryDate有关,但这是在黑暗中拍摄,没有更多细节。

【讨论】:

  • 上一篇文章中也出现了该错误,但在这种情况下,当我添加“c.emailaddr is not null”时,查询运行良好。
猜你喜欢
  • 1970-01-01
  • 2010-12-24
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-06-02
相关资源
最近更新 更多