Subscribe to How-To Geek Підписатись на How-To Geek

Important! This is an automatic machine translated page. If you can read english, you should Click Here to read the original English version of the article.

Search For Rows With Special Characters in SQL Server Пошук рядків зі спеціальними символами в SQL Server

While troubleshooting a programming problem today I noticed that you can't use a LIKE search for string columns containing special characters like % or _ without using a special syntax. Хоча усунення несправностей програмування Сьогодні я помітила, що ви не можете використовувати такі як пошук по рядку колонки, які містять спеціальні символи, такі як% або _, не використовуючи спеціальний синтаксис. Figuring out the problem took only a few minutes, but remembering syntax is always easier if you write about it. Щоб розібратися з проблемою прийняв лише кілька хвилин, але, згадавши, синтаксис завжди легше, якщо ви напишіть про нього.

So yes, this post is solely for my benefit. Так що так, ця посада тільки для моїх інтересах. Hopefully it will help somebody else too. Сподіваємося, це допоможе хтось інший теж.

Let's say you want to find any fields that contain the text “100%”, so you put together this query: Припустимо, ви хочете знайти будь-які поля, що містять текст "100%", так що ви разом узяті цього запиту:

SELECT * FROM tablename WHERE fieldname LIKE '%100%%' SELECT * from TableName%, де FieldName LIKE '% 100%'

Instead of what you wanted, you'll get all the rows that contain “100″ as well as the rows that contain “100%”. Замість того, що ви хотіли, ви отримаєте всі рядки, що містять "100", а також рядки, що містять "100%".

The problem here is that SQL Server uses the percent sign, underscore, and square brackets as special characters. Проблема тут у тому, що SQL Server використовує знак відсотка, підкреслення і квадратні дужки, оскільки спеціальні символи. You simply can't use them as a plain character in a LIKE query without escaping them. Ви просто не можете їх використовувати як простий символ в подібного запиту, не уникнути їх.

Square Bracket Escape Квадратні дужки Escape

You can surround the % or _ with square brackets to tell SQL Server that the character inside is a regular character. Ви можете оточити% або _ квадратні дужки, щоб сказати, що SQL Server характеру всередині регулярний характер.

SELECT * FROM tablename WHERE fieldname LIKE '%100[%]%' SELECT * from TableName%, де FieldName LIKE '100 [%]%'

T-SQL ESCAPE Syntax T-SQL ESCAPE Синтаксис

Alternatively, you can append the ESCAPE operator onto your query, and add a \ character before the value you want to escape. Крім того, ви можете додати ESCAPE оператор на ваш запит і додати символ \ перед значенням ви хочете сховатися.

SELECT * FROM tablename WHERE fieldname LIKE '%100\%%' ESCAPE '\' SELECT * from TableName%, де FieldName LIKE '100 \%% 'ESCAPE' \ '

The ESCAPE '\' part of the query tells the SQL engine to interpret the character after the \ as a literal character instead of as a wildcard. ESCAPE '\' Частина прохання вказує SQL двигун інтерпретувати символ після \ як буквальний характер, а не як шаблон.

Personally I find the second method easier to deal with, and you can use it to escape a square bracket as well. Особисто я вважаю, другий метод простіше мати справу, і ви можете використовувати його для втечі квадратні дужки, а також.

This article was originally written on 11/8/07 Tagged with: Ця стаття була спочатку написана на 11/8/07 тегами: Geek Stuff Незвичайні

Daily Email Updates Email Щоденні оновлення

You can get our how-to articles in your inbox each day for free. Ви можете отримати наші довідкові статті у Вашу поштову скриньку щодня безкоштовно. Just enter your name and email below: Просто введіть ваші ім'я та адресу електронної пошти нижче:


Name: Ім'я:
Email: Електронна пошта:

Comments (2) Коментарі (2)

  1. Whatever-ishere Whatever-ishere

    thanks for the GREAT post! спасибо большое за пост! Very useful… Дуже корисно ...

  2. Ashutosh Mahamia Ashutosh Mahamia

    This write up was extremely beneficial for me . Це писати було надзвичайно корисним для мене. Thanks for writing it. Спасибі, що написали його. Keep it up. Тримайте його вгору.


Our Friends Наші друзі
Getting Started Приступаючи до роботи


About How-To Geek Про How-To Geek
What Is That Process? Що це за процес?
svchost.exe svchost.exe
jusched.exe jusched.exe
dwm.exe dwm.exe
ctfmon.exe Ctfmon.exe
wmpnetwk.exe wmpnetwk.exe
wmpnscfg.exe wmpnscfg.exe
rundll32.exe rundll32.exe
wfcrun32.exe wfcrun32.exe
Ipoint.exe Ipoint.exe
Itype.exe Itype.exe
Wfica32.exe Wfica32.exe
Mobsync.exe Mobsync.exe
conhost.exe conhost.exe
Dpupdchk.exe Dpupdchk.exe Adobe_Updater.exe Adobe_Updater.exe

Copyright © 2006-2009 HowToGeek.com. Copyright © 2006-2009 HowToGeek.com. All Rights Reserved. Всі права захищені.