Перейти к содержимому

Sql как найти символ в строке

  • автор:

Функции CHARINDEX и PATINDEX

Здесь необязательный целочисленный параметр стартовая_позиция определяет позицию в строковом выражении, начиная с которой выполняется поиск. Если этот параметр опущен, поиск выполняется от начала строкового_выражения. Например, запрос

Консоль

Следует отметить, что если искомая подстрока либо строковое выражение есть NULL , то результатом функции тоже будет NULL .

Следующий пример определяет позиции первого и второго вхождения символа a в имени корабля California:

Консоль

Обратите внимание, что при определении второго символа в функции CHARINDEX используется стартовая позиция, которой является позиция следующего за первой буквой a символа — CHARINDEX(‘a’, name)+1 . Правильность результата — 2 и 10 — легко проверить.

Функция PATINDEX имеет следующий синтаксис:

Главное отличие этой функции от CHARINDEX заключается в том, что поисковая строка может содержать подстановочные знаки — % и _. При этом концевые знаки % являются обязательными. Например, использование этой функции в первом примере будет иметь вид

Консоль

SQL Server CHARINDEX Function

Summary: in this tutorial, you will learn how to use the SQL Server CHARINDEX() function to search for a substring in a string.

SQL Server CHARINDEX() function overview

SQL Server CHARINDEX() function searches for a substring inside a string starting from a specified location. It returns the position of the substring found in the searched string, or zero if the substring is not found. The starting position returned is 1-based, not 0-based.

The following shows the syntax of the CHARINDEX() function:

  • substring is the substring to search for. Its length is limited to 8,000 characters.
  • string can be a literal string, expression or column. It is a string to search.
  • start_location is the location at which the search starts. The start_location is an integer, big integer or an expression that evaluates to a value of those data types.

The start_location parameter is optional. If it is skipped, zero, or negative value, the search starts at the beginning of the string .

Note that the CHARINDEX() function can perform both case-sensitive and case-insensitive searches based on the specified collation.

SQL Server CHARINDEX() function examples

Let’s take some examples of using the CHARINDEX() function.

A) Using CHARINDEX() to perform a single search

The following example uses the CHARINDEX() function to perform a simple search of the string ‘SQL’ in the ‘SQL Server CHARINDEX’

Here is the output:

B) Using CHARINDEX() function to perform a case-insensitive search

This statement shows a case-insensitive search for the string ‘SERVER’ in ‘SQL Server CHARINDEX’ :

Here is the output:

C) Using CHARINDEX() function to perform a case-sensitive search

The following example shows a case-sensitive search for the string ‘SERVER’ in searched string SQL Server CHARINDEX .

Here is the output:

D) Using CHARINDEX() function to search for a nonexistent substring

The following example illustrates a search for the substring ‘needle’ in the string ‘This is a haystack’

E) Using CHARINDEX() function to searching from a specific position

This example uses the start_location parameter to start the search for ‘is’ at the fifth and tenth character of the string ‘This is a my sister’ :

Here is the output:

In this tutorial, you have learned how to use the SQL Server CHARINDEX() function to search for a substring in a string starting from a specified location and return the position of the substring.

T-SQL Regular Expressions: SUBSTRING, PATINDEX, and CHARINDEX

<coding>Sight» width=»44″ height=»44″ /></p>
<p>In my previous article about T-SQL regular expressions, I have explained the LIKE operator, its usage and provided several examples with it. In this article, we are going to discuss the SUBSTRING, PATINDEX, and CHARINDEX functions of T-SQL. These functions can be used to perform pattern matching.</p>
<p>First, let me explain the SUBSTRING function and provide examples with it.</p>
<h2>SUBSTRING</h2>
<p>SQL Server SUBSTRING() function is used to extract the substring from the given input_string. It extracts the substring, starting from the specified position defined by the parameter.<br />Following is the syntax for the SUBSTRING()</p>
<p>SUBSTRING() function accepts following parameters:</p>
<ol>
<li><strong>Input_string.</strong> This parameter defines a string expression from which you want to extract the substring. This parameter can be text, character, or binary string.</li>
<li><strong>Starting_position.</strong> This parameter defines a starting position from where you want to extract the substring. This parameter must be an integer value. You can use only one starting position parameter.</li>
<li><strong>Length.</strong> This parameter defines a position of the character you want to extract from the input string. This parameter must be an integer value.</li>
</ol>
<p>The following are the examples of the SUBSTRING function.</p>
<h3>Example 1: Use SUBSTRING using literal string input</h3>
<p>For example, I want to extract the word “DBA” from the input string “<strong>Nisarg is DBA</strong>.” In an input string, the position of the character D is eleven, and we want to extract three characters, therefore, the value of the “<strong>starting_position</strong>” parameter is 11, and the value of the “<strong>length</strong>” parameter is 3.</p>
<p>To do that, execute the following:</p>
<p>Following is the output:</p>
<h3>Example 2: Use SUBSTRING within T-SQL Query</h3>
<p>I have created a sample table named “IPDREGISTRATION” in the VSData database. In the table, there is a column named “IPDREGNO,” which represents patients’ registration number. The IPDREGNO is a unique number and its format is <IP> <Financial_Year><6 digit IncrementalNumber>. For example, IP1920000001.</p>
<p>I want to retrieve only six-digit numbers from the IPDREGNo column. According to the conditions, we want to trim the <IP> <Financial_Year> from the input column, therefore, the value of <strong>starting_position</strong> is seven and the value of <strong>length parameter</strong> will be six.<br />Execute the following query:</p>
<p>Following is the output:</p>
<h3>Example 3: Extract the domain name from the email address</h3>
<p>For example, I want to extract the domain name from the email address field of any table. To achieve that, we will use the substring and CHARINDEX() function. The following script can be used to extract the domain name from the email address.</p>
<p>As you can see in the above script, the CHARINDEX() function searches the string after @ and adds +1 to mark it as the start position of a string. Then it uses the LEN function to get the endpoint.</p>
<p>Following is the output:</p>
<p>Using this script, we can also find the count of an email address for each domain name. To do that we will use the COUNT function and GROUP BY clause. The following script does this task:</p>
<p>Following is the output:</p>
<h2>CHARINDEX</h2>
<p>SQL Server CHARINDEX() function is used to search the position of a substring inside an input string. Unlike SUBSTRING(), this function starts the search from a specified location and returns the position of the substring. If a substring is not found, it returns zero. CHARINDEX() function is used to perform case sensitive and case insensitive searches based on the collation specified in the query.<br />Following is the syntax of the CHARDINDEX() function.</p>
<p>CHARINDEX() accepts three arguments:</p>
<ol>
<li><strong>Substring.</strong> This argument defines the substring that you want to search within the input string.</li>
<li><strong>Input_string.</strong> This argument defines the input string.</li>
<li><strong>Start_location.</strong> This argument defines the location from which you want to start the search within the input string. The data type of this parameter is an integer, and this is an optional parameter. If this parameter is not specified, then the search starts from the beginning of the input string.</li>
</ol>
<p>The following are the examples of CHARINDEX function.</p>
<h3>Example 1: Use CHARINDEX using literal string input</h3>
<p>For example, I want to check the position of the “example” substring from the input string “This is CHARINDEX example”. To do that, execute the following query:</p>
<p>Following is the output:</p>
<p>Now, execute the following query:</p>
<p>Following is the output:</p>
<h3>Example 2: Perform case-sensitive search</h3>
<p>As I mentioned above, we can perform a case-sensitive search using the CHARINDEX function. To do that we have to use COLLATE function within a query, For example, I want to get the position of “CHARINDEX” substring from the input string “This is CHARINDEX example” To do that execute the following query:</p>
<p>Following is the output:</p>
<p>As you can see from the above, we have used case-sensitive collate, therefore the position of the word “CHARINDEX” is zero. Now, execute the following query:</p>
<p>Following is the output:</p>
<p>As you can see, the query returned the position of the word “CHARINDEX” from the input string.</p>
<h3>Example 3: Get the database file name using the T-SQL function</h3>
<p>For example, I want to populate the database and log file name of all databases. To get the file names, we are going to use a dynamic management view named sys.master_files. Execute the following query to create a function.</p>
<p>Now, let me show you how to use this function. To get the file name, execute the following query:</p>
<p>Following is the output:</p>
<h2>PATINDEX</h2>
<p>The SQL Server PATINDEX() function returns the position of a pattern within an input string. Following is the syntax of PATINDEX():</p>
<p>The PATINDEX() function accepts two parameters:</p>
<p><strong><em>1. String_Pattern.</em> </strong>This parameter defines character expression that you want to find in the input string. In the pattern, it contains the wildcard characters like % and ‘_’. The wild-card characters are the same as those used in LIKE operators.</p>
<p><strong><em>2. input_string.</em> </strong>This parameter defines an input string in which you want to search the pattern.</p>
<p>The PATINDEX() function returns the position of the first occurrence of a pattern in a string. If a pattern is not found within a string, this function returns Zero. If you pass NULL as an input_parameter, it returns NULL. PATINDEX() searches pattern is based on the collation of the input parameter. We can use the COLLATE clause to use specific collation.</p>
<p>The following are the SQL Server PATINDEX() function examples.</p>
<h3>Example 1: Use PATINDEX in a literal string input</h3>
<p>Let’s consider a simple example of PATINDEX. For example, I want to find the position of the word “example” in the “Wild-card example” input string. To do that, execute the following query:</p>
<p>Following is the output:</p>
<h3>Example 2: Use of PATINDEX with wildcards</h3>
<p>We can use wild-card characters to find the position of a specific word within an input string. In the following example, we use % and _ wild-card to find the position of a word in which the first two characters are “Wi”, followed by any other two characters and -card in input string “PATINDEX Wild-card example”.</p>
<h2>SQL CHARINDEX</h2>
<p><img decoding=

We use the SQL CHARINDEX function to find the position of a substring or expression in a given string. We might have a character in different positions of a string. SQL CHARINDEX returns the first position and ignores the rest of matching character positions in a string.

SQL CHARINDEX Function Syntax

It takes following parameters in SQL CHARINDEX function.

  • expression_to_find: In this parameter, we specify a character or string that we want to search in another string
  • expression_to_search: We can specify a string or sentence in which we want to search expression_to_find
  • start_location: It is an optional parameter. We can specify an integer value in this parameter to specify start location. If we want to search expression_to_find in expression_to_search with a specified start location, we can specify it. By default, if we do not mention any value in this parameter, it starts a search from the index position 0

Example 1: Search a character position in a string

In this example, we want to find position of @ character in a specified email address rajendra.gupta16@gmail.com

In the following screenshot, we can see position of each character in the email address string. The character ‘@’ is in position 17. We get this position in output of SQL CHARINDEX.

SQL CHARINDEX examples

Example 2: Use of optional parameter Start_position in SQL CHARINDEX

Similarly, let’s search dot (.) position in this string. We can see that the dot is on position 9th and 23rd in the specified string (email address).

Once we execute this script, it returns the first position of the dot in the output. It starts the search from starting position of a string and stops once it finds a suitable match.

SQL CHARINDEX examples

Suppose we want to get the position of the second dot (.) in this email address. We can specify a value for an optional parameter to start searching from a specific position. It starts from a specific character position and checks for the character position. We still get the actual position of the character that is 23rd in this example.

SQL Server CharIndex example

Example 3: Search a substring position in a specified string in SQL CHARINDEX

In previous examples, we searched a specific character in a specified string. We can also search a substring as well in a string.

In the following query, we declared a variable @ExpressionToSearch for the string and set a value on it. We want to search for substring Rajendra in this string.

It searches for the substring in a specified string. If it gets an exact match of the substring, it returns the starting position of the substring.

Search a substring position in a specified string

If an exact match is not found it returns 0 in the output.

Search a substring position in a specified string

Example 4: Search a substring position in a specified string with multiple matching in SQL CHARINDEX

Suppose we want to search a substring in a specified string. In the string we have multiple matching substrings. For example, in the following query, we want to search for SQLShack and find its position.

Search a substring position in a specified string with multiple matching

We can use start_location in SQL CHARINDEX with a substring as well. For example, let’s start with position 24 and see the result. It starts from character position 24 and searches for a particular substring. We can see the substring starting position is now at 63.

Search a substring position in a specified string with multiple matching

Example 5: SQL CHARINDEX with SQL CASE statement

We can use SQL CHARINDEX with SQL Case statement to search a particular substring existence in a specified string.

In the following screenshot, we can see that SQL CHARINDEX function checks for a particular substring. If it returns a value greater than 0 it means substring exists in specified string else it does not exist.

  • Substring SQLShack exists in a specified string that’s why the output is Exists
  • Substring Rajendra does not exist in a specified string that’s why the output is Not Exists

SQL CASE statement

Example 6: Case sensitive search with SQL CHARINDEX

In the previous examples, we did not use case sensitive search. For example, in the following query, we want to search for substring sqlshack in our string. This substring exists does but it exists in upper case.

It does not perform case sensitive search, and we still get the correct output.

SQL Server CASE statement

We can use collation to perform case sensitive search. In the following examples, we use COLLATE Latin1_General_CS_AS to perform case sensitive search. We need to note that all character case in a substring should match within a string. Execute the following query to understand this.

Case Sensitive search in SQL Server

Example 7: SQL CHARINDEX and table column

We can use SQL CHARINDEX for existing data in a table. We can use it to get output in a separate column. In the following example, we want to check the position of character R in empname column values of the Employee table.

In the following screenshot, we have a new column to get position of character R in EmpName column values. If Empname does not contain specified character R, it returns 0.

example of table column with SQL Server charindex

Let’s update one record in Employee table and replace empname with NULL.

Rerun the SQL CHARINDEX query, and we see value NULL in Position of R column. If we have a NULL value in a column, it also returns a NULL value.

example of table column with SQL Server charindex

Example 8: SQL CHARINDEX and Numeric value

We can search for numeric value as well as using SQL CHARINDEX. Suppose we want to find a position of character 1 in empid column of the employee table.

Search Numeric value in a string

We need to specify numeric value as well in single quotes. If we do not put single quotes, it gives following error message.

Quick Recap of SQL CHARINDEX

  • SQL CHARINDEX Returns a position of a substring within a string
  • If the target string varchar(max), nvarchar(max), it returns Big Int value else it returns Int data type
  • By default, it performs a case insensitive search
  • If there is no match found, it returns 0 in return

Conclusion

In this article, we explored SQL CHARINDEX function and its usage with various examples. Please feel free to provide feedback or ask questions in the comment section below.

Hi! I am Rajendra Gupta, Database Specialist and Architect, helping organizations implement Microsoft SQL Server, Azure, Couchbase, AWS solutions fast and efficiently, fix related issues, and Performance Tuning with over 14 years of experience.

I am the author of the book «DP-300 Administering Relational Database on Microsoft Azure». I published more than 650 technical articles on MSSQLTips, SQLShack, Quest, CodingSight, and SeveralNines.

I am the creator of one of the biggest free online collections of articles on a single topic, with his 50-part series on SQL Server Always On Availability Groups.

Based on my contribution to the SQL Server community, I have been recognized as the prestigious Best Author of the Year continuously in 2019, 2020, and 2021 (2nd Rank) at SQLShack and the MSSQLTIPS champions award in 2020.

Добавить комментарий

Ваш адрес email не будет опубликован. Обязательные поля помечены *