T-SQL 中的 IndexOf 函数

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/1869465/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-01 04:41:46  来源:igfitidea点击:

IndexOf function in T-SQL

sqlsql-servertsqlstring

提问by DevelopingChris

Given an email address column, I need to find the position of the @ sign for substringing.

给定一个电子邮件地址列,我需要找到用于子串的 @ 符号的位置。

What is the indexoffunction, for strings in T-SQL?

indexofT-SQL 中字符串的函数是什么?

Looking for something that returns the position of a substring within a string.

寻找返回字符串中子字符串位置的东西。

in C#

在 C# 中

var s = "abcde";
s.IndexOf('c'); // yields 2

回答by Scott Ivey

CHARINDEXis what you are looking for

CHARINDEX正是您要找的

select CHARINDEX('@', '[email protected]')
-----------
8

(1 row(s) affected)

-or-

-或者-

select CHARINDEX('c', 'abcde')
-----------
3

(1 row(s) affected)

回答by OMG Ponies

You can use either CHARINDEXor PATINDEXto return the starting position of the specified expression in a character string.

您可以使用CHARINDEXPATINDEX返回字符串中指定表达式的起始位置。

CHARINDEX('bar', 'foobar') == 4
PATINDEX('%bar%', 'foobar') == 4

Mind that you need to use the wildcards in PATINDEX on either side.

请注意,您需要在两侧的 PATINDEX 中使用通配符。

回答by richardtallent

One very small nit to pick:

一个非常小的尼特选择:

The RFC for email addresses allows the first part to include an "@" sign if it is quoted. Example:

电子邮件地址的 RFC 允许第一部分在引用时包含“@”符号。例子:

"john@work"@myemployer.com

This is quite uncommon, but could happen. Theoretically, you should split on the last"@" symbol, not the first:

这种情况并不常见,但可能会发生。从理论上讲,您应该拆分最后一个“@”符号,而不是第一个:

SELECT LEN(EmailField) - CHARINDEX('@', REVERSE(EmailField)) + 1

More information:

更多信息:

http://en.wikipedia.org/wiki/Email_address

http://en.wikipedia.org/wiki/Email_address

回答by Justin Swartsel

I believe you want to use CHARINDEX. You can read about it here.

我相信你想用CHARINDEX. 你可以在这里阅读它。