联接表中的错误:无效的长度参数传递给LEFT或SUBSTRING函数

时间:2019-01-14 17:42:12

标签: sql sql-server

我正在从库存快照表捕获库存数据。我已经为快照表编写了一个视图,该视图工作正常,但是当我将其连接到另一个表时,出现错误“无效的长度参数传递给LEFT或SUBSTRING函数”。尚不清楚是什么原因造成的

以下代码是我为概述快照表而构建的视图

Private Sub Worksheet_BeforeDoubleClick(ByVal Target As Range, Cancel As Boolean)

    If Target.Columns = 1 And Target.Row >= 12 Then
        dateVariable = CalendarForm.GetDate
        Target = dateVariable
    End If

End Sub

正如我提到的,此查询运行良好。

下面的视图是导致错误的原因。如您所见,我正在对现有库存表进行左连接以获取全局库存视图。

Select 
qty_ordered W_QtyOrdered, 
qty_shipped WQty_Shipped, 
on_hand_1 WOnHand, 
item_no, 

CASE 
WHEN Item_no IS NULL THEN 'Z00000'
ELSE LEFT(item_no, LEN(item_no) - 4) 
END AS ItemNo

from westrock.inventory where inventory._modified >= (select 
max(_modified) from westrock.inventory)

2 个答案:

答案 0 :(得分:2)

您应处理少于4个字符的item_no

Select 
  qty_ordered W_QtyOrdered, 
  qty_shipped WQty_Shipped, 
  on_hand_1 WOnHand, 
  item_no, 

  CASE 
    WHEN Item_no IS NULL THEN 'Z00000'
    WHEN LEN(item_no) <= 4 THEN item_no
    ELSE LEFT(item_no, LEN(item_no) - 4) 
  END AS ItemNo
from westrock.inventory 
where inventory._modified >= (select max(_modified) from westrock.inventory)

答案 1 :(得分:1)

很难得到什么?如果长度小于4,则会出现错误。因此,将逻辑更改为:

(CASE WHEN Item_no IS NULL THEN 'Z00000'
      WHEN LEN(item_no) <= 4 THEN item_no
      ELSE LEFT(item_no, LEN(item_no) - 4) 
 END) AS ItemNo