I am trying to better understand a problem that occured recently in production.
A query that has been running without issues suddenly stops with the error:
Invalid length parameter passed to the LEFT or SUBSTRING function.
The query (somewhat simplified):
SELECT t.client
FROM acuhistr t
,acuheader h
,acrclient c
WHERE t.ext_inv_ref IN (
SELECT substring(ext_inv_ref, 1, len(ext_inv_ref) - 3)
FROM acutrans
WHERE ext_inv_ref LIKE '%ROT'
AND client = t.client
)
AND t.apar_id = h.apar_id
AND c.client = t.client
AND h.client = c.leg_act_cli
I can reproduce this error message by passing a negative length parameter to substring():
SELECT substring('test', 1, -1)
Invalid length parameter passed to the substring function.
The acutrans table does contain rows thas has an empty ext_inv_ref but those should have been filtered out by the LIKE condition. If I run the subquery by itself it runs successfully.
I also tried running the full query in the dev environment and it works.
Comparing the query plans between prod and dev it seems that the prod query plan executes the SUBSTRING() before the LIKE '%ROT' condition has been applied which causes the query to fail.
Image comparing query plans between prod and dev
Am I correct in identifying the new query plan as the cause for why the query stops working? If so, why did SQL Server generate a plan that breaks the query?
SQL Server version is 2019