0
SUBSTRING(LEFT(shortnote, CHARINDEX('Additional Comments:', shortnote)), 
CHARINDEX('Patient Instructions:', shortnote) + LEN('Patient Instructions:'),LEN(shortnote))

I'm getting the result with a bit of space and the letter A from 'Additional Comments' in all of the result.
How can i get rid of that extra letter. I don't mind any space i just want to get rid of the extra letter. The value I'm getting is between patient instructions and additional comments Thank You

1
  • Could you show a couple example strings and the desired substring?
    – Hart CO
    Commented Mar 28, 2014 at 21:17

2 Answers 2

2
SUBSTRING(
    LEFT(shortnote, CHARINDEX('Additional Comments:', shortnote)-1), 
    CHARINDEX('Patient Instructions:', shortnote) + LEN('Patient Instructions:') , LEN(shortnote))
1
  • i get invalid length parameter when i added the -1 Commented Mar 28, 2014 at 20:07
1

You have to go through charindex() - 1.

charindex() returns the index at which the search term begins, so to eliminate it you need to move 1 character left.

6
  • I keept getting ivalid length parameter could it be that one of the rows does not have that test that I'm using in the substring. Commented Mar 28, 2014 at 20:35
  • I would wrap it in a case statement that checks if charindex() returns zero. Then if there are values that do not contain the string you are looking for you can handle those.
    – Tony
    Commented Mar 28, 2014 at 20:37
  • If charindex('Additional Comments:', shortnote) returns zero then it doesn't exist and you will need to use an integer larger than the size of the field for the third param of substring. You might need to nest case statements if the other charindex can return zero.
    – Tony
    Commented Mar 28, 2014 at 20:49
  • So I just realized some of the rows don't have the words I'm using or might have one or the other. The majority are fine. I don't know how else to write this. It works without the -1 but I get that letter at the end. Commented Mar 28, 2014 at 23:07
  • Try: case when charindex('Patient Instructions:', shortnote) = 0 then case when charindex('Additional Commments:', shortnote) = 0 then shortnote else substring(shortnote, 1, charindex('Additional Comments:', shortnote) + len('Additional Comments:') - 1) end when charindex('Additional Comments:', shortnote) = 0 then substring(shortnote, charindex('Patient Instructions:', shortnote) - 1, len(shortnote)) else substring(shortnote, charindex('Patient Instructions:', shortnote) + len('Patient Instructions:') - 1, charindex('Additional Comments:', shortnote) - 1) end
    – Tony
    Commented Mar 29, 2014 at 1:39

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.