1

I have CHARINDEX function with in SUBSTRING which has to identify delimiter (|) value and return the value as parameter to a substring

When delimiter is present it works fine

select SUBSTRING('SH1684|32I5', 1, CHARINDEX('|', 'SH1684|32I5') -1) AS ID

where the ID is SH1684

When it is not present

This results in error as

Msg 536, Level 16, State 1, Line 1 Invalid length parameter passed to the substring function.

But my intention is to get value in ID as SH168432I5.

How can I circumvent this problem.

3 Answers 3

5

Try this instead, by adding the delimiter, you can make sure it is in the correct logical position in cases where it is missing:

SELECT LEFT('SH1684|32I5', CHARINDEX('|', 'SH1684|32I5' + '|') - 1)
Sign up to request clarification or add additional context in comments.

Comments

2

Just use a CASE statement to determine if the | is present. CHARINDEX will return 0 if it's not present:

DECLARE @val VARCHAR(15) = 'SH1684|32I5'

-- show the value
SELECT @val

-- returns the section before the pipe
SELECT  CASE WHEN CHARINDEX('|', @val) > 0
             THEN SUBSTRING('SH1684|32I5', 1,
                            CHARINDEX('|', 'SH1684|32I5') - 1)
             ELSE @val
        END AS ID

-- set value without pipe
SET @val = 'SH168432I5'
-- same query returns entire value as there is no pipe
SELECT  CASE WHEN CHARINDEX('|', @val) > 0
             THEN SUBSTRING('SH1684|32I5', 1,
                            CHARINDEX('|', 'SH1684|32I5') - 1)
             ELSE @val
        END AS ID

So it will return the portion before the | if it's present, otherwise it will return the entire value.

Comments

0

please use select REPLACE('SH1684|32I5', '|', '') . This must work. Replace Function Example

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.