Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Invalid length parameter passed to the LEFT or SUBSTRING function

Tags:

tsql

I have the following description: 'Sample Product Maker Product Name XYZ - Size' and I would like to only get the value 'Product Name XYZ' from this. If this were just one row I'd have no issue just using SUBSTRING but I have thousands of records and although the initial value Sample Product Maker is the same for all products the Product Name could be different and I don't want anything after the hyphen.

What I have so far has generated the error in the header of this question.

SELECT i.Itemid,
       RTRIM(LTRIM(SUBSTRING(i.ShortDescription, 25, (SUBSTRING(i.ShortDescription, 25, CHARINDEX('-', i.ShortDescription, 25)))))) AS ProductDescriptionAbbrev,
       CHARINDEX('-', i.ShortDescription, 0) - 25  as charindexpos
FROM t_items i

I am getting 'Argument data type varchar is invalid for argument 3 of substring function'

As you can see, I am getting the value for the last line the sql statement but when I try and plug that into the SUBSTRING function I get various issues.

like image 923
brianhevans Avatar asked Oct 23 '12 20:10

brianhevans


People also ask

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

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.

What is SUBSTRING function?

SUBSTRING is a string manipulation function that manipulates all string data types (BIT, BLOB, and CHARACTER), and extracts characters from a string to create another string.

How do I slice a string in mysql?

The SUBSTRING() function extracts a substring from a string (starting at any position). Note: The SUBSTR() and MID() functions equals to the SUBSTRING() function.

How does Charindex work in SQL Server?

The CHARINDEX() function searches for a substring in a string, and returns the position. If the substring is not found, this function returns 0. Note: This function performs a case-insensitive search.


1 Answers

Chances are good you have rows where the '-' is missing, which is causing your error. Try this...

SELECT i.Itemid,
    SUBSTRING(i.ShortDescription, 22, CHARINDEX('-', i.ShortDescription+'-', 22)) AS ProductDescriptionAbbrev,
FROM t_items i
like image 86
Data Masseur Avatar answered Sep 23 '22 20:09

Data Masseur