Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Invalid length parameter passed to the LEFT or SUBSTRING function

I've seen a few of these questions asked but haven't spotted one that's helped!! I'm trying to select the first part of a postcode only, essentially ignoring anything after the space. the code i am using is

SUBSTRING(PostCode, 1 , CHARINDEX(' ', PostCode ) -1) 

However, I am getting Invalid length parameter passed to the LEFT or SUBSTRING function! There's no nulls or blanks but there are some the only have the first part. Is this what causing the error and if so what's the work around?

like image 886
GPH Avatar asked Jun 28 '13 15:06

GPH


People also ask

How do you fix invalid length parameter passed to the left or SUBSTRING function?

Solution / Work Around: This error message can easily be avoided by making sure that the integer value passed as the length to either the LEFT substring function or SUBSTRING string function is not negative. One way of checking it within the LEFT or SUBSTRING function is with the use of the CASE function.

How do you solve an invalid length parameter passed to the right function?

To avoid this error, always make sure that you pass a non-negative value to the length parameter of the SUBSTRING, LEFT and RIGHT functions. If used in conjunction with the CHARINDEX function, you can use the NULLIF function together with the ISNULL function to check if the character separator is found.

What is SUBSTRING in SQL with example?

SUBSTRING() is a text function that allows you to extract characters from a string. Its syntax is. SUBSTRING (expression, start, length) For the expression argument, you write a string literal or specify a column from which you want to extract the substring.

How do I delete a character in SQL Server?

The TRIM() function removes the space character OR other specified characters from the start or end of a string. By default, the TRIM() function removes leading and trailing spaces from a string.


1 Answers

That would only happen if PostCode is missing a space. You could add conditionality such that all of PostCode is retrieved should a space not be found as follows

select SUBSTRING(PostCode, 1 , case when  CHARINDEX(' ', PostCode ) = 0 then LEN(PostCode)  else CHARINDEX(' ', PostCode) -1 end) 
like image 177
iruvar Avatar answered Oct 15 '22 17:10

iruvar