powered by simpleCommunicator - 2.0.61     © 2026 Programmizd 02
Целевая тема:
Создать новую тему:
Автор:
Закрыть
Цитировать
Форумы / Microsoft Access [игнор отключен] [закрыт для гостей] / Like "*#*" находит цифры
25 сообщений из 25, страница 1 из 1
Like "*#*" находит цифры
    #32529042
Фотография Владимир Саныч
Скрыть профиль Поместить в игнор-лист Сообщения автора в теме
Модератор форума
Всем привет. У меня очередной глупый вопрос. Спасибо.

Пишу запрос:
SELECT * FROM MyTable WHERE sText Like "*#*"

А он мне возвращает не только те записи, где есть #, но и те, где есть ЦИФРЫ! Насчет что делать - я обошелся, заменил # на другой знак. Но почему он так себя ведет? Это так должно быть? Есть еще какие-то символы, которые себя ведут таким образом?
...
Рейтинг: 0 / 0
Like "*#*" находит цифры
    #32529044
mlena
Скрыть профиль Поместить в игнор-лист Сообщения автора в теме
Гость
Так как # - wildcard characters для чисел.
Matches any single digit.
...
Рейтинг: 0 / 0
Like "*#*" находит цифры
    #32529046
Фотография Serge Gavrilov
Скрыть профиль Поместить в игнор-лист Сообщения автора в теме
Участник
У Владимира Саныча F1 сломалась :)

? Any single character.
* Zero or more characters.
# Any single digit (0–9).
[charlist] Any single character in charlist.
[!charlist] Any single character not in charlist.
...
Рейтинг: 0 / 0
Like "*#*" находит цифры
    #32529047
mlena
Скрыть профиль Поместить в игнор-лист Сообщения автора в теме
Гость
В догонку:

авторЕсть еще какие-то символы, которые себя ведут таким образом?
The asterisk (*), percent sign (%), question mark (?), underscore character (_), number sign (#), exclamation point (!), hyphen (-), and brackets ([ ]) are wildcard characters
...
Рейтинг: 0 / 0
Like "*#*" находит цифры
    #32529050
Фотография Владимир Саныч
Скрыть профиль Поместить в игнор-лист Сообщения автора в теме
Модератор форума
Понял. Спасибо. А что делают % и _?
...
Рейтинг: 0 / 0
Like "*#*" находит цифры
    #32529054
Фотография Shuhard
Скрыть профиль Поместить в игнор-лист Сообщения автора в теме
Участник
sql под access и sql под mssql имеют РАЗНЫЕ wildcard для LIKE
не обижайся но поиск по конфе по Like даст уйму ссылок
...
Рейтинг: 0 / 0
Like "*#*" находит цифры
    #32529058
Фотография Shuhard
Скрыть профиль Поместить в игнор-лист Сообщения автора в теме
Участник
/topic/94666
...
Рейтинг: 0 / 0
Like "*#*" находит цифры
    #32529059
Фотография Владимир Саныч
Скрыть профиль Поместить в игнор-лист Сообщения автора в теме
Модератор форума
:^) Молчу, молчу, молчу... Я предупреждал, что вопрос глупый.
...
Рейтинг: 0 / 0
Like "*#*" находит цифры
    #32529061
Фотография Владимир Саныч
Скрыть профиль Поместить в игнор-лист Сообщения автора в теме
Модератор форума
То, что в SQL сервере вайлдкарды другие, я знал. Но ведь не могут в одном селекте использоваться и те, и другие. Чего ж они их одним списком дают? Просто перестраховка, чтобы дрессировать программеров?
...
Рейтинг: 0 / 0
Like "*#*" находит цифры
    #32529070
(c)VIG
Скрыть профиль Поместить в игнор-лист Сообщения автора в теме
Участник
Чего ж они их одним списком дают?
Для Access также важно какая система доступа используется (DAO -"*",ADO-"%"), поэтому и дают одним списком.
...
Рейтинг: 0 / 0
Like "*#*" находит цифры
    #32529078
Фотография Владимир Саныч
Скрыть профиль Поместить в игнор-лист Сообщения автора в теме
Модератор форума
Но ведь все равно не в одном селекте...
...
Рейтинг: 0 / 0
Like "*#*" находит цифры
    #32529081
(c)VIG
Скрыть профиль Поместить в игнор-лист Сообщения автора в теме
Участник
Но ведь все равно не в одном селекте...
...
Рейтинг: 0 / 0
Like "*#*" находит цифры
    #32529089
Фотография Владимир Саныч
Скрыть профиль Поместить в игнор-лист Сообщения автора в теме
Модератор форума
То есть на мой вопрос от 22:04 ответа нет.
...
Рейтинг: 0 / 0
Like "*#*" находит цифры
    #32529092
Фотография Shuhard
Скрыть профиль Поместить в игнор-лист Сообщения автора в теме
Участник
Для форсу бандитского
...
Рейтинг: 0 / 0
Like "*#*" находит цифры
    #32529093
Фотография Владимир Саныч
Скрыть профиль Поместить в игнор-лист Сообщения автора в теме
Модератор форума
А это действительно ответ.
...
Рейтинг: 0 / 0
Like "*#*" находит цифры
    #32529669
Фотография Victosha
Скрыть профиль Поместить в игнор-лист Сообщения автора в теме
Участник
авторТо, что в SQL сервере вайлдкарды другие, я знал. Но ведь не могут в одном селекте использоваться и те, и другие. Чего ж они их одним списком дают? Просто перестраховка, чтобы дрессировать программеров?

Очень на то похоже - ИМЕННО - ДРЕССИРОВАТЬ.

Саныч, Like-ов много, хороших и разных. тем, которые акцессники, чаще всего три/четыре встречаются.
Это Like, Like и Like.

Первый из них - двухместный ОПЕРАТОР VBA, возвращающий логическое значение. Именно про него F1 в VBA-справке рассказывает (он от опшон Compare зависим - явного места для указания способа сравнения в самом операторе нет). И в НЕМ, как я понимаю % - вовсе никакой не бланковый символ, а просто себе сам, % - ОБЫЧНЫЙ такой символ.

Второй И Третий - те, которые являюстя операторами SQL диалектов, наиболее часто используемых в паре с Акцесс - Jet и SQL Server.
Jet Like - всегда БЫЛ (или мне так казалось) по исполнению совместим с VBA оператором, однако, в справке Jet-4 % явно указан как равнозначный * И _ как равнозначный ?. Сейчас уже не смогу проверить - всегда ли так было (в смысле предыдущих версий) или нет, но что-то мне говорит, что НЕТ и введено "для увеличения совместимости" синтаксиса Jet запросов с SQL-Server запросами и в версии 97 работать % и _ НЕ БУДУТ. Во Всяком случае, в Jet4, поведение этого Like уже точно отличается от VBA Like-а. SQL Server Like и так всегда своей жизнью жил.

В качестве четвертого можно указать Like, живущий в VBS. Тут я все еще надеюсь, что он с VBA Like-ом вполне совместим.
...
Рейтинг: 0 / 0
Like "*#*" находит цифры
    #32529673
Фотография Владимир Саныч
Скрыть профиль Поместить в игнор-лист Сообщения автора в теме
Модератор форума
Да, спасибо. Теперь у меня все по полочкам.
...
Рейтинг: 0 / 0
Like "*#*" находит цифры
    #32529685
Фотография Shuhard
Скрыть профиль Поместить в игнор-лист Сообщения автора в теме
Участник
Код: plaintext
1.
в версии  97  работать % и _ НЕ БУДУТ
и не работают
...
Рейтинг: 0 / 0
Like "*#*" находит цифры
    #32529823
Bely
Скрыть профиль Поместить в игнор-лист Сообщения автора в теме
Участник
В Access 2002 в настройках наблюдаю опцию: "SQL serverCompatible syntax (ANSI 92)".
Когда игрался с ней и выяснял на что она влияет - влияет в том числе и на какого типа wildcard будет использоваться.

т.е. если синтак совместим, то правильные становятся % и _
иначе - они просто символы
...
Рейтинг: 0 / 0
Like "*#*" находит цифры
    #32529839
Фотография Victosha
Скрыть профиль Поместить в игнор-лист Сообщения автора в теме
Участник
2 Bely - ценное наблюдение. я его упустил.
особенно интересным оказалось то, что хелп под эту опцию подкладывает.
Чрезвычайно. Оказывается, это еще и поведение "планировщика запросов" меняет.

Все это показалось, настолько интересным, что полез читать - что же там все-таки хелп на джет по этому поводу в ТОЧНОСТИ пишет. Тоже пользительно, и опцией "срослось".

а пишут там следующее:

справка Using Wildcard Characters in String Comparisons
Built-in pattern matching provides a versatile tool for making string comparisons. The following table shows the wildcard characters you can use with the Like operator and the number of digits or strings they match.

Character(s) in pattern Matches in expression
? or _ (underscore) Any single character
* or % Zero or more characters
# Any single digit (0 — 9)
[charlist] Any single character in charlist
[!charlist] Any single character not in charlist


You can use a group of one or more characters (charlist) enclosed in brackets ([ ]) to match any single character in expression, and charlist can include almost any characters in the ANSI character set, including digits. You can use the special characters opening bracket ([ ), question mark (?), number sign (#), and asterisk (*) to match themselves directly only if enclosed in brackets. You cannot use the closing bracket ( ]) within a group to match itself, but you can use it outside a group as an individual character.

In addition to a simple list of characters enclosed in brackets, charlist can specify a range of characters by using a hyphen (-) to separate the upper and lower bounds of the range. For example, using [A-Z] in pattern results in a match if the corresponding character position in expression contains any of the uppercase letters in the range A through Z. You can include multiple ranges within the brackets without delimiting the ranges. For example, [a-zA-Z0-9] matches any alphanumeric character.

It is important to note that the ANSI SQL wildcards (%) and (_) are only available with Microsoft® Jet version 4.X and the Microsoft OLE DB Provider for Jet. They will be treated as literals if used through Microsoft Access or DAO .
Other important rules for pattern matching include the following:

An exclamation mark (!) at the beginning of charlist means that a match is made if any character except those in charlist are found in expression. When used outside brackets, the exclamation mark matches itself.
You can use the hyphen (-) either at the beginning (after an exclamation mark if one is used) or at the end of charlist to match itself. In any other location, the hyphen identifies a range of ANSI characters.
When you specify a range of characters, the characters must appear in ascending sort order (A-Z or 0-100). [A-Z] is a valid pattern, but [Z-A] is not.
The character sequence [ ] is ignored; it is considered to be a zero-length string (“”).
See Also
Like Operator SQL Expressions

Стало быть, Акцесс ИксПИ умеет по своему отнестить к последнему предложению, из выделенного синим куска.
--------------
у меня все-таки остались вопросы...
эх, не забыть бы об этом...
...
Рейтинг: 0 / 0
Like "*#*" находит цифры
    #32529841
Фотография Victosha
Скрыть профиль Поместить в игнор-лист Сообщения автора в теме
Участник
мда... впрочем - как всегда...
пояснения - приведен кусок хелпа из JetSQl40.CHM

кроме него умомянут хелп на опцию - там живет вот что

Access Help About ANSI SQL query mode
Some of the content in this topic may not be applicable to some languages.

You can create SQL queries in one of two ANSI SQL query modes:

ANSI-89 describes the traditional Jet SQL syntax. This mode conforms closely to the ANSI-89 Level 1 specification, but is not ANSI-89 Level 1 compliant. Certain ANSI-89 SQL features are not implemented and the wildcard characters conform to the Visual Basic for Applications (VBA) specification, not SQL.
ANSI-92 provides new reserved words, syntax rules, and wildcard characters that enhance your ability to create queries, filters, and SQL statements. This mode conforms closely to the ANSI-92 Level 1 specification, but is not ANSI-92 Level 1 compliant. This query mode has more of the ANSI syntax, and the wildcard characters conform to the SQL specification.
In Microsoft Access 2000 using ADOX, you could programmatically create queries that used ANSI-92 SQL syntax. However, any queries you created were not visible in the Database window because there was no option to set this mode in the user interface. Now in Access 2002, you can set the ANSI SQL query mode through the user interface for the current database and as the default setting for new databases.

Why use ANSI-92 SQL?

You may want to use ANSI-92 SQL for the following reasons:

You anticipate upsizing your application in the future to an Access project and want to create queries that will run with minimal changes in a Microsoft SQL Server database.
You want to take advantage of the new features not found in ANSI-89 SQL, such as:
Changing security settings by using the GRANT and REVOKE SQL statements
Using DISTINCT in an aggregate function reference, for example, SUM(DISTINCT Price)
Using the LIMIT TO nn ROWS clause to limit the number of rows returned by a query
Why you should avoid mixing queries created under different ANSI SQL query modes

The two ANSI SQL query modes, ANSI-89 and ANSI-92, are not compatible. When you create a Microsoft Access database, you need to decide which query mode you are going to use, because mixing queries created in both query modes could produce runtime errors or unexpected results. The range of data types, reserved words, and wildcard characters are different in each query mode.

Example of a query using wildcard characters

A query that uses wildcard characters in a criteria expression can produce different results under each query mode. For example, if you run:

An ANSI-89 SQL query in a database set to ANSI-92 query mode, such as:
SELECT * FROM Customers WHERE Country Like 'U*'

It returns all customers from a country/region named "U*", not all countries/regions beginning with the letter "U", because the asterisk (*) is not a wildcard character in ANSI-92 SQL.

An ANSI-92 SQL query in a database set to ANSI-89 query mode, such as:
SELECT * FROM Customers WHERE Country Like 'U%'

It returns all customers from a country/region named "U%", not all countries/regions beginning with the letter "U", because the percent sign (%) is not a wildcard character in ANSI-89 SQL.

Example of a query with a duplicate field and alias name

If a query uses an alias that is the same as a base column name and you create a calculated field using the ambiguous name, the query will produce different results under each query mode. For example, if you run the following query:

SELECT Orders.OrderID AS Freight, Orders.Freight, [Freight]*1.1 AS [New Freight] FROM Orders;

Under ANSI-92 SQL, Access calculates the New Freight value using the Freight field, and therefore increases each Freight by 10%. Under ANSI-89 SQL, Access calculates the New Freight value using the Freight alias, and therefore increases each OrderID by 10%.

How to avoid problems caused by mixing queries under different ANSI SQL query modes in the same database

In general, avoid doing the following to prevent problems caused by mixing queries created under different ANSI SQL query modes:

Converting an Access database set to ANSI-92 SQL query mode from 2002 file format to 2000 or 97 file format. ANSI-92 SQL query mode is only supported in the 2002 file format.
Changing the ANSI SQL query mode for the current database after you've created one or more queries. If you must do this, retest the existing queries to ensure that they still run or produce expected results, and rewrite the queries if necessary.
Importing queries created under one ANSI SQL query mode into an Access database set to another mode, or exporting queries created under one ANSI SQL query mode to an Access database set to another mode.
Changing the ANSI SQL query mode in an existing application. This could break your application and require rewriting your application.
In Access 2000, you can only programmatically change the ANSI SQL query mode and any queries created under ANSI-92 mode were hidden in the Database window. In Access 2002, you or a user can change ANSI SQL query mode through the user interface and ANSI-92 queries are no longer hidden in the Database window, so you should prevent accidental or intentional changes to the ANSI SQL query mode of your application by protecting your code and preventing the changing of the query mode through the application's user interface.

Using ambiguous aliases and column names. To avoid confusion, ensure that aliases and column names are always unique in an SQL statement.

The ANSI SQL query mode default for new Access databases in 2002 and 2000 file formats

ANSI-89 is the default setting for a new Access database in 2002 and 2000 file format.
You cannot set the SQL query mode new database default to ANSI-92 in 2000 file format because the option is disabled; ANSI-89 is the only query mode setting available for a database in Access 2000 file format.
...
Рейтинг: 0 / 0
Like "*#*" находит цифры
    #32530397
фыыф
Скрыть профиль Поместить в игнор-лист Сообщения автора в теме
Гость
работает:
Like "*[#]*"
...
Рейтинг: 0 / 0
Like "*#*" находит цифры
    #32530403
в догонку
Скрыть профиль Поместить в игнор-лист Сообщения автора в теме
Гость
кстати у меня 97
Like "*#*"
не находит #, но ТОЛЬКО цифры (что и должно быть)
...
Рейтинг: 0 / 0
Like "*#*" находит цифры
    #32530549
Фотография Владимир Саныч
Скрыть профиль Поместить в игнор-лист Сообщения автора в теме
Модератор форума
в догонкуно ТОЛЬКО цифры (что и должно быть)
Да, так и есть. У меня в одних и тех же строках были и цифры, и #.
...
Рейтинг: 0 / 0
Like "*#*" находит цифры
    #32530556
Фотография Владимир Саныч
Скрыть профиль Поместить в игнор-лист Сообщения автора в теме
Модератор форума
фыыфработает:
Like "*[#]*"
Проблема в том, что опция меню Filter by Selection при выделении знака # строит фильтр Like "*#*", а не Like "*[#]*", и в результате работает неправильно. У меня этот топик возник именно после такого эффекта.
...
Рейтинг: 0 / 0
25 сообщений из 25, страница 1 из 1
Форумы / Microsoft Access [игнор отключен] [закрыт для гостей] / Like "*#*" находит цифры
Найденые пользователи ...
Разблокировать пользователей ...
Читали форум (0):
Пользователи онлайн (0):
x
x
Закрыть


Просмотр
0 / 0
Close
Debug Console [Select Text]