问题
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!!!
回答1:
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.
回答2:
If charindex
doesn't find that character, it returns 0 so all you need to do is
select col, charindex('A', col) + charindex('B', col) as position
from your_table;
Another alternative
select col, charindex('A', replace(col, 'B', 'A')) as position
from your_table;
DEMO
来源:https://stackoverflow.com/questions/60120460/how-to-use-charindex-for-one-or-the-other-character