Invalid length parameter passed to the LEFT or SUBSTRING function
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
Your first call to SUBSTRING
specifies a length of SUBSTRING(i.ShortDescription, 25, CHARINDEX('-', i.ShortDescription, 25))
.
You might try:
declare @t_items as Table ( ItemId Int Identity, ShortDescription VarChar(100) )
insert into @t_items ( ShortDescription ) values
( 'Sample Product Maker Product Name XYZ - Size' )
declare @SkipLength as Int = Len( 'Sample Product Maker' )
select ItemId,
RTrim( LTrim( Substring( ShortDescription, @SkipLength + 1, CharIndex( '-', ShortDescription, @SkipLength ) - @SkipLength - 1 ) ) ) as ProductDescriptionAbbrev
from @t_items
You could also strip out the Sample Product Maker
text and go from there:
SELECT RTRIM(LEFT(
LTRIM(REPLACE(i.ShortDescription, 'Sample Product Maker', '')),
CHARINDEX('-', LTRIM(REPLACE(i.ShortDescription, 'Sample Product Maker',
'' ))) - 1))
AS ShortDescription
The problem is that your outer call to SUBSTRING
is being passed a character data type from the inner SUBSTRING
call in the third parameter.
+--This call does not return an integer type
SELECT i.Itemid, V
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
The third parameter must evaluate to the length that you want. Perhaps you meant LEN(SUBSTRING(...))
?