Home > OS >  How to check in SQL which character occurs first in a string
How to check in SQL which character occurs first in a string

Time:06-08

I have a column with string values which I need to parse based on which of the 2 characters occurred first - @ and /.

Can you please help me with a SQL select query that will check the string? The possible scenarios are:

  • Both @ and / are present in the string, if so which one comes first
  • Only 1 of the character occurs in the string

CodePudding user response:

You could use a combination of charindex and outer apply & values, from which you can select the first-occuring character:

select t.*, FirstChar
from t
outer apply(
    select top (1) FirstChar
    from (values
          (CharIndex('@',string),'@'),
          (CharIndex('/',string),'/')
    )v(i,FirstChar)
    where i > 0
    order by i
)x;

Demo enter image description here

  •  Tags:  
  • sql
  • Related