0

我正在尝试执行 SQL ServerSUBSTRING查询,但它抛出错误。

查询是:

select 
    substring(testcasename, 2, 5) val1, 
    substring(testcasename, 2, CHARINDEX(',', testcasename, 2) - 2) val2 
from 
    tce_lineno 
where 
    testcasename <> '' and project='proj001'

错误是:

消息 537,级别 16,状态 5,第 1 行
传递给 LEFT 或 SUBSTRING 函数的长度参数无效。

这个查询有什么问题吗?

4

2 回答 2

1

As I mentioned in comments When testcasename does not have , then CHARINDEX(',',testcasename,2) will return 0 so Substring will fail.

To fix that use case statement, When , is not found use length of testcasename

SELECT Substring(testcasename, 2, 5)   val1,
       Substring(testcasename, 2, CASE
                                    WHEN Charindex(',', testcasename, 2) > 2 THEN Charindex(',', testcasename, 2) - 2
                                    ELSE Len(testcasename)
                                  END) val2
FROM   tce_lineno
WHERE  testcasename <> ''
       AND project = 'proj001' 
于 2015-02-04T05:06:03.393 回答
0

将此子句添加到 where

和 testcasename 之类的 '%,%'

发生错误是因为某些记录中没有逗号 (,)

于 2015-02-04T06:28:44.700 回答