Fix issue with "invalid length parameter passed to the left or substring function".

mo boy 396 Reputation points
2022-11-10T10:58:20.603+00:00

Dear experts,

There is this code but it appears to fail with this message.

"invalid length parameter passed to the left or substring function". Please advise how to fix this?
This is not the whole code but this is where the issue lies as I don't see anywhere else in the code using substring function.

substring(emp_list.[Pay Department], 1, charindex('-', emp_list.[Pay Department]) - 2) AS 'Division Name',

CASE when (len(emp_list.[Pay Department]) - len(replace(emp_list.[Pay Department],'-',''))) < 2
THEN ''
ELSE substring((right(emp_list.[Pay Department],(len(emp_list.[Pay Department]) - (CHARINDEX('-', emp_list.[Pay Department])+1)))), 1, charindex('-', (right(emp_list.[Pay Department],(len(emp_list.[Pay Department]) - (CHARINDEX('-', emp_list.[Pay Department])+1))))) - 2)
END AS 'Unit Name'

Thanks

Developer technologies | Transact-SQL
Developer technologies | Transact-SQL
A Microsoft extension to the ANSI SQL language that includes procedural programming, local variables, and various support functions.
SQL Server | Other
{count} vote

Answer accepted by question author
  1. LiHongMSFT-4306 31,616 Reputation points
    2022-11-11T01:56:44.22+00:00

    Hi @mo boy
    At the first glance of this issue, this may cause by your source data.
    Check this sample: select substring('abc',1,charindex('-','abc') - 2) which will receive same error message.
    CHARINDEX will return 0 if no '-' are in the string and then you look for a substring of **0 - 2 = -2 ** length.

    Therefore, you'd better check if there is any special data in the source data table that causes the function to return a negative number. You can split these functions such as charindex to check which one returns a negative value.

    Best regards,
    LiHong


    If the answer is the right solution, please click "Accept Answer" and kindly upvote it. If you have extra questions about this answer, please click "Comment".
    Note: Please follow the steps in our Documentation to enable e-mail notifications if you want to receive the related email notification for this thread.


0 additional answers

Sort by: Most helpful

Your answer

Answers can be marked as 'Accepted' by the question author and 'Recommended' by moderators, which helps users know the answer solved the author's problem.