Wednesday, September 17, 2025

sql server - How to solve problem with CHARINDEX() - value subtraction

If you use this SQL code:
SUBSTRING( a.PackingSlipId, 1, CHARINDEX('-', a.PackingSlipId ) - 1 ) as document,
..you can get this error, even in a situation when CHARINDEX() returns valid values: Output:
Msg 537, Level 16, State 3, Line 1
Invalid length parameter passed to the LEFT or SUBSTRING function.
The solution is to use NULLIF() function:
SUBSTRING( a.PackingSlipId, 1, nullif( CHARINDEX('-', a.PackingSlipId ), 0 ) -1 ) as document,

No comments:

Post a Comment