andy47
andy47

Reputation: 913

How to find first occurrence of one of a sequence of characters in T-SQL

I would like to write a simple query to find the first occurrence of either ',' or ';' in a string within T-SQL. Is there any easy way to do this?

In other databases I would use a regular expression such as [,;] but these aren't available in T-SQL.

The only solution I can think of is to have a long list of nested if .. else statements but that doesn't appeal.

Upvotes: 3

Views: 11733

Answers (2)

Gareth McCaughan
Gareth McCaughan

Reputation: 19981

I am vastly ignorant of T-SQL, but looking at Microsoft's documentation it seems like CHARINDEX will find the first occurrence of a single character (or in fact of any string), and you can just call it twice (once for , and once for ;) and see which one occurs first. See: http://msdn.microsoft.com/en-US/library/ms186323%28v=sql.90%29.aspx .

Upvotes: 0

Alex
Alex

Reputation: 2420

Try PATINDEX...

select patindex('%,%', my_column)
from my_table

Upvotes: 7

Related Questions