1

I've got a column 'Title' and it holds values similar to this text here

HotelBeds SLU: Refugi Dels Isards Hotel in Pas de la Casa, Andorra (4 nights)

I'd want to select anything that comes after the colon (:) and exclude anything after the comma.

I tried this:

Select SUBSTRING(title,
            CHARINDEX(':',title)+1,
          CHARINDEX(',',title)
          -CHARINDEX(':',title)-1) HotelName from booking_tbl

I see this error

Invalid length parameter passed to the LEFT or SUBSTRING function.

What am I doing wrong?

1
  • 1
    Its exactly as the error says? The values you are passing to sub-string are wrong. Select the charindex values without using the sub-string and you'll soon work out what you are doing wrong. Commented Feb 26, 2020 at 6:45

3 Answers 3

3

You can try this using CHARINDEX (Transact-SQL).

This function searches for one character expression inside a second character expression, returning the starting position of the first expression if found.

Syntax

CHARINDEX ( expressionToFind , expressionToSearch [ , start_location ] ) 

Implementation

DECLARE @x varchar(max) = 'HotelBeds SLU: Refugi Dels Isards Hotel in Pas de la Casa, Andorra (4 nights)'
SELECT
  RTRIM(LEFT( @x , CHARINDEX(':',  @x ))) AS PartA,
  SUBSTRING( @x , CHARINDEX(':',  @x ) + 1, 8000) AS PartB

db<>fiddle Demo

Sign up to request clarification or add additional context in comments.

Comments

1

You need to append the , or : as becuase some titles don't have , or : :

SELECT SUBSTRING(title, CHARINDEX(':',title + ':') + 1, 
                 CHARINDEX(',', title + ',') - CHARINDEX(':',title + ':') 
                ) HotelName 
FROM booking_tbl bt;

You can either add where clause to avoid error :

WHERE CHARINDEX(',', tittle) > 0 AND
      CHARINDEX(':', title) > 0;

Comments

1
declare @str nvarchar(250)
set @str = 'HotelBeds SLU: Refugi Dels Isards Hotel in Pas de la Casa, Andorra (4nights)';
select ltrim(
 substring(
  @str, 
  charindex(':', @str) + 1, 
  charindex(',', @str) - (charindex(':', @str) + 1)
 )
)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.