【问题标题】:Invalid Length Parameter passed to Left or substring function error传递给左或子字符串函数错误的长度参数无效
【发布时间】:2021-06-17 04:30:24
【问题描述】:

我使用的是 SQL Server 2016:

select 
    a.ID, v.Comments, 
    left(v.rest, patindex('%[^$0-9]%', v.rest + ' ') - 1) as amount
from 
    Table a 
cross apply
    (values (rtrim(left(Comments charindex('$', Comments-1 )),
            stuff(Comments, 1, charindex('$', Comments) -1, ''))) v (Comments, rest)
where 
    ID v.Comments = 'AAAAAAAAAAA MAXIMUM LIABILITY $67,650 NO LONGER QUA'

我遇到了一个错误

传递给左或子字符串函数的长度参数无效。

我的目标是拆分字符串和数值,例如

AAAAAAAAAAA MAXIMUM LIABILITY          67,650

以下是我的表格Comments 列中的数据示例

'AAAAAAAAAAA MAXIMUM LIABILITY $67,650 NO LONGER QUA'
'BBBBBBBBBBB MAXI   LILIABILITY $$44,77.00-LAND
'CCCCCCCCCCC MAXIU  LIABILITY   $12,44.90"

【问题讨论】:

  • 总是最好在你的 charindex 中添加一个“Fail-Safe”。例如: charindex('$', Comments+'$') 注意 +'$'
  • 嗨,约翰。我正在尽我所能,但没有工作。
  • 您可以使用NULLIF(PATINDEX(...), 0)以防找不到匹配项

标签: sql sql-server


【解决方案1】:

您在交叉应用部分发布的查询存在一些拼写错误。我还在 patindex 中添加了一个逗号 (,) 以包含所有价格。

select 
    a.ID, v.Comments, 
    left(v.rest, patindex('%[^$0-9,]%', v.rest + ' ') - 1) as amount
from a 
cross apply
    (values (rtrim(left(Comments, charindex('$', Comments)-1 )),
            stuff(Comments, 1, charindex('$', Comments) -1, ''))) v (Comments, rest)

如果你愿意,你也可以正确地添加你的位置。

where a.Comments = 'AAAAAAAAAAA MAXIMUM LIABILITY $67,650 NO LONGER QUA'

这里有一个sqlfiddle 向您展示它是如何工作的

【讨论】:

  • 非常感谢。它的工作。有什么办法可以跳过$?只需要 67,650 。提前致谢
  • 我看到您也有用于美分的句点 ('.')。所以我将它添加到 patindex,对于 $ 符号我只是添加了一个替换。 REPLACE(left(v.rest, patindex('%[^$0-9,.]%', v.rest + ' ') - 1),'$','') as amount.
  • 谢谢亚尔。 100% 工作
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2021-07-19
  • 2016-06-09
  • 1970-01-01
  • 2019-08-30
  • 2013-01-11
  • 2023-03-14
  • 2014-03-01
相关资源
最近更新 更多