• Главная
  • Карта сайта
Не найдено

LIKE (Transact-SQL) - SQL Server

  1. синтаксис Syntax
  2. аргументи Arguments
  3. Типи результату Result Types
  4. Значення результату Result Value
  5. Використання символу-шаблону «%» Using the% Wildcard Character
  6. Використання символів-шаблонів в якості литералов Using Wildcard Characters As Literals
  7. Збіг з шаблоном за допомогою пропозиції ESCAPE Pattern Matching with the ESCAPE Clause
  8. приклади Examples
  9. Г. D. Використання символів-шаблонів [] Using the [] wildcard characters
  10. Приклади: Сховище даних SQL Azure Azure SQL Data Warehouse і Паралельне сховище даних Parallel Data...
  11. Див. Також: See Also

ОБЛАСТЬ ЗАСТОСУВАННЯ: ОБЛАСТЬ ЗАСТОСУВАННЯ:   SQL Server   База даних SQL Azure   Сховище даних SQL Azure   Parallel Data Warehouse APPLIES TO:   SQL Server   Azure SQL Database   Azure SQL Data Warehouse   Parallel Data Warehouse   Визначає, чи збігається зазначена символьний рядок з заданим шаблоном SQL Server База даних SQL Azure Сховище даних SQL Azure Parallel Data Warehouse APPLIES TO: SQL Server Azure SQL Database Azure SQL Data Warehouse Parallel Data Warehouse

Визначає, чи збігається зазначена символьний рядок з заданим шаблоном. Determines whether a specific character string matches a specified pattern. Шаблон може включати звичайні символи і символи-шаблони. A pattern can include regular characters and wildcard characters. Під час порівняння з шаблоном необхідно, щоб його звичайні символи в точності збігалися з символами, зазначеними в рядку. During pattern matching, regular characters must exactly match the characters specified in the character string. Символи-шаблони можуть збігатися з довільними елементами символьного рядка. However, wildcard characters can be matched with arbitrary fragments of the character string. Використання символів-шаблонів на відміну від використання операторів порівняння рядка (= і! =) Робить оператор LIKE більш гнучким. Using wildcard characters makes the LIKE operator more flexible than using the = and! = String comparison operators. Якщо тип даних одного з аргументів не є символьним рядком, компонент Компонент SQL Server Database Engine SQL Server Database Engine, якщо це можливо, перетворює його в тип даних символьного рядка. If any one of the arguments is not of character string data type, the Компонент SQL Server Database Engine SQL Server Database Engine converts it to character string data type, if it's possible.

Синтаксичні позначення в Transact-SQL   Transact-SQL Syntax Conventions Синтаксичні позначення в Transact-SQL Transact-SQL Syntax Conventions

синтаксис Syntax

- Syntax for SQL Server and Azure SQL Database match_expression [NOT] LIKE pattern [ESCAPE escape_character] - Syntax for Azure SQL Data Warehouse and Parallel Data Warehouse match_expression [NOT] LIKE pattern

аргументи Arguments

match_expression match_expression
Будь-яке допустиме вираз expression символьного типу даних. Is any valid expression of character data type.

pattern pattern
Конкретна рядок символів для пошуку в match_expression може містити наступні допустимі символи-шаблони. Is the specific string of characters to search for in match_expression , and can include the following valid wildcard characters. Довжина значення pattern не може перевищувати 8000 байт. pattern can be a maximum of 8,000 bytes.

Символ-шаблон Wildcard character Опис Description Приклад Example% Будь-яка рядок, що містить нуль або більше символів. Any string of zero or more characters. Інструкція WHERE Назва LIKE '% комп'ютер%' виконує пошук і видає всі назви книг, що містять слово «комп'ютер». WHERE title LIKE '% computer%' finds all book titles with the word 'computer' anywhere in the book title. _ (Підкреслення) _ (underscore) Будь-який одиночний символ. Any single character. Інструкція WHERE фамілія_автора LIKE '_етров' виконує пошук і видає всі імена, що складаються з шести букв і закінчуються поєднанням «етров» (Петров, Вєтров і т.п.). WHERE au_fname LIKE '_ean' finds all four-letter first names that end with ean (Dean, Sean, and so on). [] [] Будь-який одиночний символ, що міститься в діапазоні ([af]) або наборі ([abcdef]). Any single character within the specified range ([af]) or set ([abcdef]). Інструкція WHERE Фамілія_автора LIKE '[Л-С] омов' виконує пошук і видає всі прізвища авторів, що закінчуються на «омов» і починаються на будь-яку букву в проміжку від «Л» до «С», наприклад Ломов, Ромів, Сомов і т. п. WHERE au_lname LIKE '[CP] arsen' finds author last names ending with arsen and starting with any single character between C and P, for example Carsen, Larsen, Karsen, and so on. При виконанні операції пошуку в діапазоні символи, включені в діапазон, можуть змінюватися в залежності від правил сортування параметрів сортування. In range searches, the characters included in the range may vary depending on the sorting rules of the collation. [^] [^] Будь-який одиночний символ, що не міститься в діапазоні ([^ af]) або наборі ([^ abcdef]). Any single character not within the specified range ([^ af]) or set ([^ abcdef]). Інструкція WHERE Фамілія_автора LIKE 'верб [^ а]%' виконує пошук і видає всі прізвища, що починаються на "верб", в яких третя буква відрізняється від "а". WHERE au_lname LIKE 'de [^ l]%' all author last names starting with de and where the following letter is not l.

escape_character escape_character
Символ, що поміщається перед символом-шаблоном для того, щоб символ-шаблон розглядався як звичайний символ, а не як шаблон. Is a character put in front of a wildcard character to indicate that the wildcard is interpreted as a regular character and not as a wildcard. Аргумент escape_character є символьним виразом, що не мають значення за замовчуванням і повертає результат у вигляді одного символу. escape_character is a character expression that has no default and must evaluate to only one character .

Типи результату Result Types

Boolean Boolean

Значення результату Result Value

Оператор LIKE повертає значення TRUE, якщо аргумент match_expression співпадає з аргументом pattern. LIKE returns TRUE if the match_expression matches the specified pattern .

При використанні оператора LIKE для порівняння рядків до уваги беруться всі символи рядка-шаблона. When you do string comparisons by using LIKE, all characters in the pattern string are significant. До значущим символам також відносяться початкові і кінцеві пробіли. Significant characters include any leading or trailing spaces. Якщо операція порівняння в запиті повинна повернути всі рядки, що містять рядки LIKE 'абв' (з символом пробілу на кінці), то рядок, що містить "абв" (без пробілу), не буде повернута. If a comparison in a query is to return all rows with a string LIKE 'abc' (abc followed by a single space), a row in which the value of that column is abc (abc without a space) is not returned. Однак завершальні прогалини в вираженні, з яким порівнюється шаблон, не враховуються. However, trailing blanks, in the expression to which the pattern is matched, are ignored. Якщо операція порівняння в запиті повинна повернути всі рядки, що містять рядки LIKE 'абв' (без знака пробілу на кінці), то будуть повернуті всі рядки, що містять «абв», як із завершальними пробілами, так і без них. If a comparison in a query is to return all rows with the string LIKE 'abc' (abc without a space), all rows that start with abc and have zero or more trailing blanks are returned.

При порівнянні рядків за допомогою оператора LIKE з використанням шаблону, що містить тип даних char і varchar, можуть виникнути проблеми через методи зберігання кожного типу даних. A string comparison using a pattern that contains char and varchar data may not pass a LIKE comparison because of how the data is stored for each data type . В ході виконання такого прикладу локальна змінна char передається збереженій процедурі, а потім за допомогою порівняння з шаблоном виконується пошук всіх співробітників, чиї прізвища починаються з зазначеній послідовності букв. The following example passes a local char variable to a stored procedure and then uses pattern matching to find all employees whose last names start with the specified set of characters .

- Uses AdventureWorks CREATE PROCEDURE FindEmployee @EmpLName char (20) AS SELECT @EmpLName = RTRIM (@EmpLName) + '%'; SELECT p.FirstName, p.LastName, a.City FROM Person.Person p JOIN Person.Address a ON p.BusinessEntityID = a.AddressID WHERE p.LastName LIKE @EmpLName; GO EXEC FindEmployee @EmpLName = 'Barb'; GO

Виконання процедури FindEmployee не дає результатів, так як змінна типу char (@EmpLName) завжди має довжину в 20 символів, до якої доповнюється завершальними знаками пробілу. In the FindEmployee procedure, no rows are returned because the char variable (@EmpLName) contains trailing blanks whenever the name contains fewer than 20 characters. Змінні, що містяться в стовпці LastName, мають тип varchar. Тому завершальні прогалини в них не дописують. Because the LastName column is varchar, there are no trailing blanks. Дана процедура завершується невдачею, так як завершальні прогалини враховуються. This procedure fails because the trailing blanks are significant.

Процедура з такого прикладу виконується успішно, так як завершальні прогалини до змінної типу varchar не повинні додаватися. However, the following example succeeds because trailing blanks are not added to a varchar variable .

- Uses AdventureWorks CREATE PROCEDURE FindEmployee @EmpLName varchar (20) AS SELECT @EmpLName = RTRIM (@EmpLName) + '%'; SELECT p.FirstName, p.LastName, a.City FROM Person.Person p JOIN Person.Address a ON p.BusinessEntityID = a.AddressID WHERE p.LastName LIKE @EmpLName; GO EXEC FindEmployee @EmpLName = 'Barb';

Нижче наводиться результуючий набір. Here is the result set.

FirstName LastName City ---------- -------------------- --------------- Angela Barbariol Snohomish David Barber Snohomish (2 row (s) affected)

Оператор LIKE підтримує зіставлення шаблонів в ASCII і Юникоде. LIKE supports ASCII pattern matching and Unicode pattern matching. Якщо всі аргументи (match_expression, pattern і escape_character, якщо він вказаний) мають символьний тип ASCII, то застосовується шаблон ASCII. When all arguments (match_expression, pattern, and escape_character, if present) are ASCII character data types, ASCII pattern matching is performed. Якщо який-небудь з аргументів має тип даних Юнікоду, виконується перетворення всіх аргументів в Юнікод і застосовується шаблон Юникода. If any one of the arguments are of Unicode data type, all arguments are converted to Unicode and Unicode pattern matching is performed. Якщо ви використовуєте оператор LIKE з типом даних Юнікоду (nchar або nvarchar), завершальні прогалини враховуються на відміну від інших типів даних (НЕ Юникода). When you use Unicode data (nchar or nvarchar data types) with LIKE, trailing blanks are significant; however, for non-Unicode data, trailing blanks are not significant. Оператор LIKE, який використовується з даними Юнікод, підтримує стандарт ISO. Unicode LIKE is compatible with the ISO standard. Оператор LIKE, який використовується з даними ASCII, підтримує більш ранні версії SQL Server SQL Server. ASCII LIKE is compatible with earlier versions of SQL Server SQL Server.

У наступних прикладах показані відмінності в рядках, що повертаються при зіставленні шаблонів Юникода і ASCII з використанням оператора LIKE. The following is a series of examples that show the differences in rows returned between ASCII and Unicode LIKE pattern matching.

- ASCII pattern matching with char column CREATE TABLE t (col1 char (30)); INSERT INTO t VALUES ( 'Robert King'); SELECT * FROM t WHERE col1 LIKE '% King'; - returns 1 row - Unicode pattern matching with nchar column CREATE TABLE t (col1 nchar (30)); INSERT INTO t VALUES ( 'Robert King'); SELECT * FROM t WHERE col1 LIKE '% King'; - no rows returned - Unicode pattern matching with nchar column and RTRIM CREATE TABLE t (col1 nchar (30)); INSERT INTO t VALUES ( 'Robert King'); SELECT * FROM t WHERE RTRIM (col1) LIKE '% King'; - returns 1 row

Примітка

Операції порівняння за допомогою оператора LIKE залежать від параметрів сортування. LIKE comparisons are affected by collation. Додаткові відомості див. У розділі COLLATE (Transact-SQL) . For more information, see COLLATE (Transact-SQL) .

Використання символу-шаблону «%» Using the% Wildcard Character

Якщо в операторі LIKE вказати символ '5%', то компонент Компонент Database Engine Database Engine буде шукати число «5», за яким слід будь-який рядок з числом символів від нуля і більше. If the LIKE '5%' symbol is specified, the Компонент Database Engine Database Engine searches for the number 5 followed by any string of zero or more characters.

Наприклад, при виконанні наступного прикладу відображаються всі динамічні адміністративні уявлення бази даних AdventureWorks2012 AdventureWorks2012, так як всі вони починаються символами dm. For example, the following query shows all dynamic management views in the AdventureWorks2012 AdventureWorks2012 database , because they all start with the letters dm.

- Uses AdventureWorks SELECT Name FROM sys.system_views WHERE Name LIKE 'dm%'; GO

Щоб відобразити всі об'єкти, які не є динамічними адміністративними уявленнями, використовується синтаксис NOT LIKE 'dm%'. To see all objects that are not dynamic management views, use NOT LIKE 'dm%'. Наприклад, якщо за все мається 32 об'єкти і оператор LIKE видає 13 найменувань, які збігаються з шаблоном, то оператор NOT LIKE повертає 19 об'єктів, які не відповідають вказаним в операторі LIKE шаблоном. If you have a total of 32 objects and LIKE finds 13 names that match the pattern, NOT LIKE finds the 19 objects that do not match the LIKE pattern.

За таким шаблоном, як LIKE '[^ d] [^ m]%', не завжди будуть повертатися одні й ті ж імена. You may not always find the same names with a pattern such as LIKE '[^ d] [^ m]%'. Замість 19 імен можна знайти тільки 14, так як імена, які починаються з літери d або у яких другий буквою є m, будуть виключені з результату, як і імена динамічних адміністративних уявлень. Instead of 19 names, you may find only 14, with all the names that start with d or have m as the second letter eliminated from the results, and the dynamic management view names. Причиною такої реакції на подію є поетапний пошук негативних символів-шаблонів: за один крок обробляється один символ-шаблон. This behavior is because match strings with negative wildcard characters are evaluated in steps, one wildcard at a time. Процес пошуку збігів припиняється при виникненні збою на будь-якій стадії виконання. If the match fails at any point in the evaluation, it's eliminated.

Використання символів-шаблонів в якості литералов Using Wildcard Characters As Literals

Символи-шаблони можуть бути використані в якості литералов. You can use the wildcard pattern matching characters as literal characters. Щоб використовувати символ-шаблон як литерала, його необхідно укладати в дужки. To use a wildcard character as a literal character, enclose the wildcard character in brackets. У наступній таблиці представлені кілька прикладів застосування ключового слова LIKE разом з символами-шаблонами []. The following table shows several examples of using the LIKE keyword and the [] wildcard characters.

Символ Symbol Значення Meaning LIKE '5 [%]' LIKE '5 [%]' 5% 5% LIKE '[] n' LIKE '[] n' _n _n LIKE '[a-cdf]' LIKE '[a-cdf ] 'a, b, c, d або fa, b, c, d, or f LIKE' [-acdf] 'LIKE' [-acdf] '-, a, b, c, d або f -, a, c , d, or f LIKE '[[]' LIKE '[[]' [[LIKE ']' LIKE ']']] LIKE 'abc [] d%' LIKE 'abc [] d%' abc_d і abc_de abc_d and abc_de LIKE 'abc [def]' LIKE 'abc [def]' abcd, abce і abcf abcd, abce, and abcf

Збіг з шаблоном за допомогою пропозиції ESCAPE Pattern Matching with the ESCAPE Clause

Можна шукати символьні рядки, до складу яких входить один або більше спеціальних символів-шаблонів. You can search for character strings that include one or more of the special wildcard characters. Наприклад, таблиця discounts бази даних customers може містити значення знижок, що включають знак відсотка (%). For example, the discounts table in a customers database may store discount values ​​that include a percent sign (%). Щоб виконати пошук знака відсотка як символ-шаблону, необхідно ввести ключове слово ESCAPE і escape-символ. To search for the percent sign as a character instead of as a wildcard character, the ESCAPE keyword and escape character must be provided. Наприклад, зразок бази даних містить стовпець з ім'ям comment, в якому зберігається значення «30%». For example, a sample database contains a column named comment that contains the text 30%. Щоб знайти рядки, які містять послідовність символів «30%» в стовпці comment, необхідно вказати пропозицію WHERE, наприклад WHERE comment LIKE '% 30! %%' ESCAPE '!'. To search for any rows that contain the string 30% anywhere in the comment column, specify a WHERE clause such as WHERE comment LIKE '% 30! %%' ESCAPE '!'. Якщо пропозиція ESCAPE і escape-символ не вказані, компонент Компонент Database Engine Database Engine поверне всі записи, що містять послідовність символів "30". If ESCAPE and the escape character are not specified, the Компонент Database Engine Database Engine returns any rows with the string 30.

Якщо в шаблоні LIKE після escape-символа немає ніякого символу, то шаблон є неприпустимим і оператор LIKE повертає значення FALSE. If there is no character after an escape character in the LIKE pattern, the pattern is not valid and the LIKE returns FALSE. Якщо символ після escape-символа не є символом-шаблоном, то escape-символ ігнорується, а наступний символ розглядається як звичайний символ в шаблоні. If the character after an escape character is not a wildcard character, the escape character is discarded and the following character is treated as a regular character in the pattern. До цих символів-шаблонів відносяться: підкреслення (), відсоток (%) і ліва квадратна дужка ([), в тому випадку, якщо вони укладені в квадратні дужки. These characters include the percent sign (%), underscore (), and left bracket ([) wildcard characters when they are enclosed in double brackets ([]). Escape-символи можуть використовуватися в квадратних дужках ([]), включаючи: знак вставки (^), дефіс (-) і праву квадратну дужку (]). Escape characters can be used within the double bracket characters ([]), including to escape a caret (^), hyphen (-), or right bracket (]).

Символ 0x0000 (char (0)) не визначений в параметрах сортування Windows, і його не можна включати в LIKE. 0x0000 (char (0)) is an undefined character in Windows collations and can not be included in LIKE .

приклади Examples

У наступному прикладі в таблиці 415 виконується пошук всіх телефонних номерів з кодом міста PersonPhone. The following example finds all telephone numbers that have area code 415 in the PersonPhone table.

- Uses AdventureWorks SELECT p.FirstName, p.LastName, ph.PhoneNumber FROM Person.PersonPhone AS ph INNER JOIN Person.Person AS p ON ph.BusinessEntityID = p.BusinessEntityID WHERE ph.PhoneNumber LIKE '415%' ORDER by p. LastName; GO

Нижче наводиться результуючий набір. Here is the result set.

FirstName LastName Phone ----------------- ------------------- ----------- - Ruben Alonso 415-555-124 Shelby Cook 415-555-0121 Karen Hu 415-555-0114 John Long 415-555-0147 David Long 415-555-0123 Gilbert Ma 415-555-0138 Meredith Moreno 415-555-0131 Alexandra Nelson 415-555-0174 Taylor Patterson 415-555-0170 Gabrielle Russell 415-555-0197 Dalton Simmons 415-555-0115 (11 row (s) affected) `` `### B. Using NOT LIKE with the% wildcard character The following example finds all telephone numbers in the `PersonPhone` table that have area codes other than` 415`. `` `Sql - Uses AdventureWorks SELECT p.FirstName, p.LastName, ph.PhoneNumber FROM Person.PersonPhone AS ph INNER JOIN Person.Person AS p ON ph.BusinessEntityID = p.BusinessEntityID WHERE ph.PhoneNumber NOT LIKE '415% 'AND p.FirstName =' Gail 'ORDER BY p.LastName; GO

Нижче наводиться результуючий набір. Here is the result set.

FirstName LastName Phone ---------------------- -------------------- ----- -------------- Gail Alexander 1 (11) 500 555-0120 Gail Butler 1 (11) 500 555-0191 Gail Erickson 834-555-0132 Gail Erickson 849-555-0139 Gail Griffin 450-555-0171 Gail Moore 155-555-0169 Gail Russell 334-555-0170 Gail Westover 305-555-0100 (8 row (s) affected) `` `### C. Using the ESCAPE clause The following example uses the `ESCAPE` clause and the escape character to find the exact character string` 10-15% `in column` c1` of the `mytbl2` table. `` `Sql USE tempdb; GO IF EXISTS (SELECT TABLE_NAME FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_NAME = 'mytbl2') DROP TABLE mytbl2; GO USE tempdb; GO CREATE TABLE mytbl2 (c1 sysname); GO INSERT mytbl2 VALUES ( 'Discount is 10-15% off'), ( 'Discount is .10-.15 off'); GO SELECT c1 FROM mytbl2 WHERE c1 LIKE '% 10-15!% Off%' ESCAPE '!'; GO

Г. D. Використання символів-шаблонів [] Using the [] wildcard characters

У наступному прикладі виконується пошук в таблиці Person співробітників з ім'ям Cheryl іліSheryl. The following example finds employees on the Person table with the first name of Cheryl or Sheryl.

- Uses AdventureWorks SELECT BusinessEntityID, FirstName, LastName FROM Person.Person WHERE FirstName LIKE '[CS] heryl'; GO

У наступному прикладі виконується пошук рядків в таблиці Person для співробітників з прізвищем Zheng або Zhang. The following example finds the rows for employees in the Person table with last names of Zheng or Zhang.

- Uses AdventureWorks SELECT LastName, FirstName FROM Person.Person WHERE LastName LIKE 'Zh [ae] ng' ORDER BY LastName ASC, FirstName ASC; GO

Приклади: Сховище даних SQL Azure Azure SQL Data Warehouse і Паралельне сховище даних Parallel Data Warehouse Examples: Сховище даних SQL Azure Azure SQL Data Warehouse and Паралельне сховище даних Parallel Data Warehouse

У наступному прикладі в таблиці DimEmployee виконується пошук всіх співробітників, телефонні номери яких починаються з 612. The following example finds all employees in the DimEmployee table with telephone numbers that start with 612.

- Uses AdventureWorks SELECT FirstName, LastName, Phone FROM DimEmployee WHERE phone LIKE '612%' ORDER by LastName;

У наступному прикладі в таблиці DimEmployee виконується пошук всіх телефонних номерів, які не починаються з 612. The following example finds all telephone numbers in the DimEmployee table that do not start with 612.. .

- Uses AdventureWorks SELECT FirstName, LastName, Phone FROM DimEmployee WHERE phone NOT LIKE '612%' ORDER by LastName;

У наступному прикладі в таблиці DimEmployee виконується пошук всіх телефонних номерів, що починаються з 2 і закінчуються на 6. The following example finds all telephone numbers that have an area code starting with 6 and ending in 2 in the DimEmployee table. Підстановлювальний знак "%" доданий в кінці шаблону пошуку, що відповідає будь-яким наступним символам в значеннях стовпця з телефонними номерами. The% wildcard character is included at the end of the search pattern to match all following characters in the phone column value.

- Uses AdventureWorks SELECT FirstName, LastName, Phone FROM DimEmployee WHERE phone LIKE '6_2%' ORDER by LastName;

Див. Також: See Also

PATINDEX (Transact-SQL) PATINDEX (Transact-SQL)
Вирази (Transact-SQL) Expressions (Transact-SQL)
Вбудовані функції (Transact-SQL) Built-in Functions (Transact-SQL)
SELECT (Transact-SQL) SELECT (Transact-SQL)
WHERE (Transact-SQL) WHERE (Transact-SQL)

Провайдеры:
  • 08.09.2015

    Batyevka.NET предоставляет услуги доступа к сети Интернет на территории Соломенского района г. Киева.Наша миссия —... 
    Читать полностью

  • 08.09.2015
    IPNET

    Компания IPNET — это крупнейший оператор и технологический лидер на рынке телекоммуникаций Киева. Мы предоставляем... 
    Читать полностью

  • 08.09.2015
    Boryspil.Net

    Интернет-провайдер «Boryspil.net» начал свою работу в 2008 году и на данный момент является одним из крупнейших поставщиков... 
    Читать полностью

  • 08.09.2015
    4OKNET

    Наша компания работает в сфере телекоммуникационных услуг, а именно — предоставлении доступа в сеть интернет.Уже... 
    Читать полностью

  • 08.09.2015
    Телегруп

    ДП «Телегруп-Украина» – IT-компания с 15-летним опытом работы на рынке телекоммуникационных услуг, а также официальный... 
    Читать полностью

  • 08.09.2015
    Софтлинк

    Высокая скоростьМы являемся участником Украинского центра обмена трафиком (UA — IX) с включением 10 Гбит / сек... 
    Читать полностью