Invalid length parameter passed to the RIGHT funct

2019-07-16 00:04发布

问题:

About 2 weeks ago some SQL that has been working for the past 6 months started throwing an error without anything changing. I spent a couple days trying to find out what was going on and it just did not make any sense.

Eventually, I tried just an "alter" on the Stored Procedure (which had no effect) and then eventually dropped and recreated it (which did fix it).

Then, 2 days ago, the error came back and this time even the drop/create is not fixing it. According to my IT guys, they have not patched the SQL Servers in 1.5 months so there was nothing changed there. Does anyone have any ideas or has had the same issues?

This line of code, in a stored procedure:

SELECT LabelText + Data
FROM CU_FormLayout fl
    INNER JOIN CU_Data dat ON dat.LayoutId = fl.Id
    CROSS APPLY (SELECT RIGHT(fl.xLabelText,1) RightChar) ca2
    CROSS APPLY (SELECT CASE WHEN ASCII(RightChar) BETWEEN 49 AND 57 OR 
                                ASCII(RightChar) BETWEEN 65 AND 90 OR 
                                ASCII(RightChar) BETWEEN 97 AND 122
                            THEN fl.xLabelText + ': '
                            ELSE fl.xLabelText + ' ' END LabelText) ca1

Causes this error:

Invalid length parameter passed to the RIGHT function.

As you can see, the only RIGHT() has a hard-coded length. How could it be invalid?

BTW, the point of this code is that it takes a "Label" from one column and if it ends with a letter or number, add ": " and then the data value the label is for. Other-wise just put a space between them.

回答1:

Perhaps if you can't find the cause (it's probably bugging production environment), you could rewrite using SUBSTRING? Or a combination of REVERSE & LEFT.