How to use Charindex for one or the other character

為{幸葍}努か 提交于 2021-02-10 20:39:52

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!