Search code examples
sqlsql-serverstringcharindex

How to use Charindex for one or the other character


I have a string with a bunch of numbers but it contains one letter somewhere in the center of the string. This letter can either be 'A' or 'B'. I am trying to find out the position of this letter with the Charindex() function. However it doesn't work when you have two search parameters:

select  charindex('[A,B]','190118A3700000')

I tried it out with a range and wildcards but it did not work. So what I want are these two separate queries combined in one:

select  charindex('A','190118A3700000')
select  charindex('B','190118A3700000')

Does anybody have an idea how to do this?

Thank you!!!


Solution

  • Use patindex():

    select patindex('%[A,B]%', '190118A3700000')
    

    Or, if you want the first non-digit:

    select patindex('%[^0-9]%', '190118A3700000')
    

    Here is a db<>fiddle.

    charindex() does not understand wildcards.