sql-server-2005t-sql

Invalid length parameter passed to the LEFT or SUBSTRING function in Sql Server


While trying to execute the below query

Declare @t table (id int, string varchar(1000))

INSERT INTO @t (id, string)
SELECT 1, 'zxzzxx,ppppbppp,trtrtr,tyyt,hgghh,fefew,rewr,rwerer' 

;WITH test (id, lft, rght, idx)
AS 
(
        SELECT t.id
                ,LEFT(t.string, CHARINDEX(', ', t.string) - 1)
                ,SUBSTRING(t.string, CHARINDEX(', ', t.string) + 2, DATALENGTH(t.string))
                ,0
        FROM @t t
        UNION ALL
        SELECT c.id
                ,CASE WHEN CHARINDEX(', ', c.rght) = 0 THEN c.rght ELSE LEFT(c.rght, CHARINDEX(', ', c.rght) - 1) END
                ,CASE WHEN CHARINDEX(', ', c.rght) > 0 THEN SUBSTRING(c.rght, CHARINDEX(', ', c.rght) + 2, DATALENGTH(c.rght)) 
                        ELSE '' END
                ,idx + 1
        FROM test c 
        WHERE DATALENGTH(c.rght) > 0
)

select id, lft from test 

I am getting the below error

Msg 537, Level 16, State 2, Line 8
Invalid length parameter passed to the LEFT or SUBSTRING function.

but the same works for SELECT 1, 'the, quick, brown, fox, jumped, over, the, lazy, dog'

Please help


Solution

  • It seems to be a space missing between your words.

    You are currently looking for charindex of ', ' not ','.

    And the string does not have any match of ', '.