1

I'm trying to cut off everything after a certain character (in this case '&') and if there is no occurence of that character, get the entire string.

select left(@str,isnull(nullif(charindex('&',@str) - 1,-1),len(@str)))

This seems to be a rather needlessly complicated way of doing it. Is there a better/shorter way?

Here is a full test case to indicate what I'm doing...

declare @str as varchar(255) 
set @str = 'abc&def&ghi'

select left(@str,isnull(nullif(charindex('&',@str) - 1,-1),len(@str)))

-- Returns 'abc'

set @str = 'abc'

select left(@str,isnull(nullif(charindex('&',@str) - 1,-1),len(@str)))

-- Returns 'abc'
5
  • What is the end result you are you trying to achieve? Is this for a report? Legacy migration? I would be a bit concerned if you are developing an app today on 2005. Commented Feb 7, 2017 at 10:15
  • Do you need to do this in a single statement? On the fly? Commented Feb 7, 2017 at 10:16
  • Can you upgrade the db? Commented Feb 7, 2017 at 10:17
  • The end result is to cut off everything after '&' from a certain field. I need to do it in a single statement. I cannot upgrade the db.
    – MrVimes
    Commented Feb 7, 2017 at 10:34
  • I'm just asking for the sake of education. In the actual use-case I will just use what I've done here. But I wondered if there's a better way because it seems overkill to use five functions for a fairly simple process.
    – MrVimes
    Commented Feb 7, 2017 at 10:36

1 Answer 1

2

Well - here is 'another' way...

DECLARE @str AS VARCHAR(255)

SET @str = 'abc&def&ghi'

SELECT CASE 
        WHEN charindex('&', @str) > 0
            THEN substring(@str, 1, charindex('&', @str) - 1)
        ELSE @str
        END AS SelectedString
-------------------------------
SET @str = 'abc'

SELECT CASE 
        WHEN charindex('&', @str) > 0
            THEN substring(@str, 1, charindex('&', @str) - 1)
        ELSE @str
        END AS SelectedString

OR - you could simply ALWAYS concatenate '&' at the end of the string like this:

DECLARE @str AS VARCHAR(255)

SET @str = 'abc&def&ghi'

SELECT substring(@str, 1, charindex('&', @str + '&') - 1)
-------------------------------
SET @str = 'abc'

SELECT substring(@str, 1, charindex('&', @str + '&') - 1)
0

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.