views:

67

answers:

5

I have this query that spawns the following error:

SELECT * FROM Quota
WHERE LEFT(QtLabel, LEN(QtLabel)-2) IN (
'1032',
'3300',
'9682'
)

Msg 536, Level 16, State 5, Line 1 Invalid length parameter passed to the SUBSTRING function.

Am I doing something wrong? It tends to show up when I use the LEN() function. Might it be a datatype issue?

+7  A: 

Is it possible that LEN(QtLabel) <= 2 ?

Dewfy
my test code shows that it is excatly this. _declare @quota table (qtlabel varchar(10)); insert into @quota values('1'); SELECT * FROM @Quota WHERE LEFT(QtLabel, LEN(QtLabel)-2) IN ('1032','3300','9682')_
KM
AH, of course. I'm so used to filtering some of the records out but I forgot to do it this time. Silly me.
Joe Philllips
+2  A: 

Are you sure that each QtLabel field is longer than 2 characters?

Josip Medved
+1  A: 

LEFT probably uses SUBSTRING internally. What happens if the length of QtLabel is <= 2?

Chris Doggett
+1  A: 

It's because some QtLabel values don't contain > 2 characters, so you end up trying to do a LEFT() with a negative value as the number to restrict to.

In your scenario, you're assuming all QtLabel values are 6 characters, so uou should do:

SELECT * FROM Quota
WHERE LEN(QtLabel) = 6
AND LEFT(QtLabel, LEN(QtLabel)-2) IN (
'1032',
'3300',
'9682'
)
AdaTheDev
+1  A: 

SELECT LEFT('MyText', -2)

will throw the same error

ck