如何查找T-SQL中字符序列之一的第一次出现

时间:2022-03-18 01:40:47

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?

我想编写一个简单的查询来查找T-SQL中的字符串中第一个出现的'、'或';有什么简单的办法吗?

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

在其他数据库中,我将使用正则表达式,如[,;],但在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.

我能想到的唯一的解决方案是有一长串嵌套的if。else语句,但这没有吸引力。

2 个解决方案

#1


7  

Try PATINDEX...

尝试PATINDEX……

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

#2


0  

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 .

我对T-SQL一无所知,但是看看微软的文档,好像CHARINDEX会找到第一个字符(或者实际上是任何字符串)的出现,您只需调用它两次(一次为,一次为;),然后看看哪个字符最先出现。参见:http://msdn.microsoft.com/en-US/library/ms186323%28v=sql.90%29.aspx。

#1


7  

Try PATINDEX...

尝试PATINDEX……

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

#2


0  

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 .

我对T-SQL一无所知,但是看看微软的文档,好像CHARINDEX会找到第一个字符(或者实际上是任何字符串)的出现,您只需调用它两次(一次为,一次为;),然后看看哪个字符最先出现。参见:http://msdn.microsoft.com/en-US/library/ms186323%28v=sql.90%29.aspx。