Sql usage in CHARINDEX

 CHARINDEX role

  We often need to write SQL statements to determine whether a string contains another string, but did not like SQL SERVER and C # provides Contains function, but SQL SERVER provides a function called CHAEINDX, by definition is to find character (char) location (index), now are able to know the location, of course, can determine whether the contained therein.

      By CHARINDEX If you can find the corresponding string position returns 0 otherwise.

      The basic syntax is as follows:

  CHARINDEX ( expressionToFind , expressionToSearch [ , start_location ] )

      expressionToFind: target string is the string you want to find the maximum length of 8000.

  expressionToSearch: for the search string.

      start_location: Find a location, the default is empty to start from the first look.

 

CHAEINDEX example

  1. Simple Usage  

  select charindex('test','this Test is Test')

  search result:  

  2. Increase the start position

  select charindex('test','this Test is Test',7)

  search result:

  3. case sensitive

  select charindex('test','this Test is Test'COLLATE Latin1_General_CS_AS)

  search result:

  Returns a value of 0? ? ? Do not doubt your eyes, because case-sensitive, so the test can not find the return is 0, default, SQL SERVER is not sensitive to size, so we have a simple example returns the result is not zero, but sometimes we need go out case sensitive, so special SQL SERVE provides a special case-sensitive keywords for queries where CS is Case-sensitve acronym.

  4. The case-insensitive

  select charindex('Test','this Test is Test'COLLATE Latin1_General_CI_AS)

  search result:

  We can explain this is not case-sensitive, which CI is Case-InSensitve acronym, that is not case sensitive, of course, we do not need to bother.

 

PATINDEX

  And CHARINDEX Similarly, the PATINDEX also be used to determine whether a string contains another string, the difference between the two is that the former is fully matched, which supports fuzzy matching.

  Example 1. Simple

  select PATINDEX ( '%% ter', 'interesting data')

  search result:

  2. Simple Example 2

  select PATINDEX ( '% t_ng%', 'interesting data')

  search result:

 

  PATINDEX also allows the support case-sensitive, and CHARINDEX practices, as here no longer tired.

  reference:

    https://docs.microsoft.com/en-us/sql/t-sql/functions/charindex-transact-sql

  https://docs.microsoft.com/en-us/sql/t-sql/functions/patindex-transact-sql

Guess you like

Origin www.cnblogs.com/shiyh/p/11024582.html