Главная страница
    Top.Mail.Ru    Яндекс.Метрика
Форум: "Начинающим";
Текущий архив: 2006.02.26;
Скачать: [xml.tar.bz2];

Вниз

NOT LIKE   Найти похожие ветки 

 
veb   (2006-02-11 19:32) [0]

Здравствуйте! Не могу в ADOTable с помощью Filter получить выборку "поле не содержит".
Т.е. выбрать фильм который не содержит жанр "комедия"
tbMovies.Filter := Format(" NOT (Genres LIKE %0:s)",[QuotedStr("%комедия%")])
что делать и как получить такую выборку?


 
Desdechado ©   (2006-02-11 19:52) [1]

может, так
tbMovies.Filter := "Upper(Genres) NOT LIKE " + QuotedStr("%КОМЕДИЯ%");


 
veb   (2006-02-11 20:26) [2]

Нет!!!
Так тоже не работает!!!


 
Desdechado ©   (2006-02-11 20:56) [3]

и что говорит?


 
Desdechado ©   (2006-02-11 20:56) [4]

я надеюсь
Filtered:=True;
?


 
veb   (2006-02-11 21:22) [5]

Говорит, что "аргументы имеют не верный тип"!
Пожалуйста, кто знает как составить верно строку фильтра для ADOTable, чтоб получить вариант выборки "строка не содержит", подскажите пожалуйста!
не работают и такие варианты
Genres <> "*комедия*"


 
veb   (2006-02-12 11:50) [6]

Народ, неужели никто не знает ответ на такой простой вопрос? Ведь не может же быть, чтоб такую выборку нельзя было сделать с помощью Filter?


 
Virgo_Style ©   (2006-02-12 14:22) [7]

Можно написать обработчик OnFilterRecord, а в нем можно использовать функцию MatchesMask


 
sniknik ©   (2006-02-12 14:41) [8]

> чтоб такую выборку нельзя было сделать с помощью Filter?
с помощью ADOTable и Filter ты не делаеш такую выборку, а делаеш полную т.е. (все 10 милионов записей или сколько у тебя там в таблице) и отфильтровываеш ее (убираеш ненужное) до 10 записей (или сколько там) значимых...

т.что слава богу, что не получается,  может хоть это сподвигнет на чтение основ/теории/и вообще любой литературы о базах...


 
Anatoly Podgoretsky ©   (2006-02-12 15:19) [9]

Формат фильтра зависит от базы и движка.


 
Desdechado ©   (2006-02-12 15:42) [10]

> "аргументы имеют не верный тип"
это намек, что поле, возможно, нетекстовое


 
veb   (2006-02-12 17:35) [11]

to Virgo_Style
 мысль! спасибо, если ничего больше не получится, то придется идти по этому пути.

to sniknik
 очень остроумно, кроме банального выпендрежа, никакой полезной информации.

to Anatoly
 Access, microsoft Jet 4.0
 я этот вопрос задавал в разделе БД там указал базу, но его обсуждение перенесли сюда, не понимаю почему, так как ответа нет. На самом деле если такую выборку сделать невозможно, то это же просто огромная недоработка движка, базы, Delphi. (нужное подчеркнуть)

to Desdechado
 спасибо конечно, за Ваши ответы, но я предлагаю искать ошибку не в моем коде, а просто написать как надо правильно настроить фильтр, если такое вообще возможно.


 
Desdechado ©   (2006-02-12 17:41) [12]

еще раз: Filter - это не выборка, это ограничение для УЖЕ ВЫБРАННЫХ записей
выборка  - это SELECT, которое для TTable делается тупо: SELECT * FROM Tablica
а не тупо - SELECT поля FROM Tablica WHERE ограничения
но это уже другие компоненты делают

> искать ошибку не в моем коде
по статистике, ошибки присутствуют везде, вот только в своем коде их на порядки больше, чем в коде компонентов, который шлифовался годами


 
veb   (2006-02-12 18:07) [13]

To Desdechado
 Народ!  Это что тонкое издевальство? Да знаю я, что такое выборка и как работают клиент-серверные и локальные БД и все остальное тоже знаю...
Не знаю вот чего:

 Конкретный вопрос: в поле ADOTable.Filter, что надо прописать чтоб получилась фильтрация ( черт с ней с "выборкой") по строковому полю вида
"поле  не содержит"


Фильтрация вида "Поле содержит" выглядит так
Filter :=  "Genres LIKE " + QuotedStr("%КОМЕДИЯ%");
Filtered := True;

и работает правильно!


 
sniknik ©   (2006-02-12 19:19) [14]

> Народ!  Это что тонкое издевальство? Да знаю я, что такое выборка... ...все остальное тоже знаю...
точно, издевательство... с твоей стороны. т.к. если знаеш то чего знаниями не пользуешся? разводиш нас грешных, на искушение поиздеваться... тонко...

> ... чтоб получилась фильтрация ...
ничего. не поддерживаются операции над операциями/полями в фильтре, т.е. если сравнение с полем типа ID = 2 работает то уже инвертировать результат NOT ID = 2 не получится, OR и AND только, да и то с ограничениями...

> to sniknik
> очень остроумно, кроме банального выпендрежа, никакой полезной информации.
хелп самая полезная информация... у твас нет? у меня есть вам - не банально
Filter Property
     
Indicates a filter for data in a Recordset.

Settings and Return Values

Sets or returns a Variant value, which can contain one of the following:

Criteria string — a string made up of one or more individual clauses concatenated with AND or OR operators.

Array of bookmarks — an array of unique bookmark values that point to records in the Recordset object.

A FilterGroupEnum value.
Remarks

Use the Filter property to selectively screen out records in a Recordset object. The filtered Recordset becomes the current cursor. Other properties that return values based on the current cursor are affected, such as AbsolutePosition, AbsolutePage, RecordCount, and PageCount. This is because setting the Filter property to a specific value will move the current record to the first record that satisfies the new value.

The criteria string is made up of clauses in the form FieldName-Operator-Value (for example, "LastName = "Smith""). You can create compound clauses by concatenating individual clauses with AND (for example, "LastName = "Smith" AND FirstName = "John"") or OR (for example, "LastName = "Smith" OR LastName = "Jones""). Use the following guidelines for criteria strings:

FieldName must be a valid field name from the Recordset. If the field name contains spaces, you must enclose the name in square brackets.

Operator must be one of the following: <, >, <=, >=, <>, =, or LIKE.

Value is the value with which you will compare the field values (for example, "Smith", #8/24/95#, 12.345, or $50.00). Use single quotes with strings and pound signs (#) with dates. For numbers, you can use decimal points, dollar signs, and scientific notation. If Operator is LIKE, Value can use wildcards. Only the asterisk (*) and percent sign (%) wild cards are allowed, and they must be the last character in the string. Value cannot be null.
Note   To include single quotation marks (") in the filter Value, use two single quotation marks to represent one. For example, to filter on O"Malley, the criteria string should be "col1 = "O""Malley"". To include single quotation marks at both the beginning and the end of the filter value, enclose the string with pound signs (#). For example, to filter on "1", the criteria string should be "col1 = #"1"#".

There is no precedence between AND and OR. Clauses can be grouped within parentheses. However, you cannot group clauses joined by an OR and then join the group to another clause with an AND, like this:
(LastName = "Smith" OR LastName = "Jones") AND FirstName = "John"

Instead, you would construct this filter as
(LastName = "Smith" AND FirstName = "John") OR (LastName = "Jones" AND FirstName = "John")

In a LIKE clause, you can use a wildcard at the beginning and end of the pattern (for example, LastName Like "*mit*"), or only at the end of the pattern (for example, LastName Like "Smit*").
The filter constants make it easier to resolve individual record conflicts during batch update mode by allowing you to view, for example, only those records that were affected during the last UpdateBatch method call.

Setting the Filter property itself may fail because of a conflict with the underlying data (for example, a record has already been deleted by another user). In such a case, the provider returns warnings to the Errors collection but does not halt program execution. A run-time error occurs only if there are conflicts on all the requested records. Use the Status property to locate records with conflicts.

Setting the Filter property to a zero-length string ("") has the same effect as using the adFilterNone constant.

Whenever the Filter property is set, the current record position moves to the first record in the filtered subset of records in the Recordset. Similarly, when the Filter property is cleared, the current record position moves to the first record in the Recordset.

See the Bookmark property for an explanation of bookmark values from which you can build an array to use with the Filter property.


 
sniknik ©   (2006-02-12 19:24) [15]

> to Virgo_Style
> мысль! спасибо, если ничего больше не получится, то придется идти по этому пути.
лучше всетаки воспользоваться знаниями о запросх...


 
veb   (2006-02-12 20:27) [16]

to sniknik
 А  вот что написано в моем хелпе:
Теперь объясните: где в выдержке из приведенного вами хелпа написано, что не поддерживается операция NOT

Filter support in client datasets
Operatoror function Example Supported by other datasets Comment
Comparisons  
= State = "CA" Yes
<> State <> "CA" Yes
>= DateEntered >= "1/1/1998" Yes
<= Total <= 100,000 Yes
> Percentile > 50 Yes
< Field1 < Field2 Yes
BLANK State <> "CA" or State = BLANK Yes Blank records do not appear unless explicitly included in the filter.
IS NULL Field1 IS NULL No
IS NOT NULL Field1 IS NOT NULL No

Logical operators  
and State = "CA" and Country = "US" Yes
or State = "CA" or State = "MA" Yes
not not (State = "CA") Yes

Arithmetic operators  
+ Total + 5 > 100 Depends on driver Applies to numbers, strings, or date (time) + number.
- Field1 - 7 <> 10 Depends on driver Applies to numbers, dates, or date (time) - number.
* Discount * 100 > 20 Depends on driver Applies to numbers only.
/ Discount > Total / 5 Depends on driver Applies to numbers only.
String functions  
Upper Upper(Field1) = "ALWAYS" No
Lower Lower(Field1 + Field2) = "josp" No
Substring Substring(DateFld,8) = "1998"Substring(DateFld,1,3) = "JAN" No Value goes from position of second argument to end or number of chars in third argument. First char has position 1.
Trim Trim(Field1 + Field2)Trim(Field1, "-") No Removes third argument from front and back. If no third argument, trims spaces.
TrimLeft TrimLeft(StringField)TrimLeft(Field1, "$") <> "" No See Trim.
TrimRight TrimRight(StringField)TrimRight(Field1, ".") <> "" No See Trim.
DateTime functions  
Year Year(DateField) = 2000 No
Month Month(DateField) <> 12 No
Day Day(DateField) = 1 No
Hour Hour(DateField) < 16 No
Minute Minute(DateField) = 0 No
Second Second(DateField) = 30 No
GetDate GetDate - DateField > 7 No Represents current date and time.
Date DateField = Date(GetDate) No Returns the date portion of a datetime value.
Time TimeField > Time(GetDate) No  Returns the time portion of a datetime value.
Miscellaneous  
Like Memo LIKE "%filters%" No Works like SQL-92 without the ESC clause. When applied to BLOB fields, FilterOptions determines whether case is considered.
In Day(DateField) in (1,7) No Works like SQL-92. Second argument is a list of values all with the same type.
* State = "M*" Yes Wildcard for partial comparisons.
When applying ranges or filters, the client dataset still stores all of its records in memory. The range or filter merely determines which records are available to controls that navigate or display data from the client dataset.


 
sniknik ©   (2006-02-12 23:12) [17]

> А  вот что написано в моем хелпе:
ты что с клиенского датасета описание выдернул?
не обратил внимание на колонку "Supported by other datasets"? позиции отмеченые "No" и "Depends on driver" (кстати с логическим not у борланда тут (и еще в паре мест) накладочка применительно к ADO...)

и, чем нибудь поближе к теме (тому чем пользуешся) не пробовал пользоваться?
а если хочеш чтобы это работало, то добавляй еще DataSetProvider с клиентским рекордсетом, перегоняй данные в него, и пользуйся там.

> где в выдержке из приведенного вами хелпа написано, что не поддерживается операция NOT
а где сказано что поддерживается?

вообще к чему сомнения, возми да проверь. ну... арифметические операции... функции... т.д. все со "своего" и "моего" хелпа. и сравни, что на самом деле работает а что нет.


 
veb   (2006-02-13 13:26) [18]

Итак, хочу просто подвести итог:

Сделать фильтрацию вида "поле не содержит указанной подстроки" с помощью свойства ADOTable.Filter в базе данных Access невозможно!

Ну что ж отрицательный результат то же результат!



Страницы: 1 вся ветка

Форум: "Начинающим";
Текущий архив: 2006.02.26;
Скачать: [xml.tar.bz2];

Наверх





Память: 0.51 MB
Время: 0.034 c
6-1132064989
Kullibin
2005-11-15 17:29
2006.02.26
Работа с компонентами FastNet


15-1139385787
Гаврила
2006-02-08 11:03
2006.02.26
Fast Report - некрасивое поведение


2-1139675549
veb
2006-02-11 19:32
2006.02.26
NOT LIKE


15-1139406227
R.T.
2006-02-08 16:43
2006.02.26
TChart не печатает на сетевой принтер


15-1139233884
PARUS
2006-02-06 16:51
2006.02.26
Нету спама!(Дуратский вопрос)





Afrikaans Albanian Arabic Armenian Azerbaijani Basque Belarusian Bulgarian Catalan Chinese (Simplified) Chinese (Traditional) Croatian Czech Danish Dutch English Estonian Filipino Finnish French
Galician Georgian German Greek Haitian Creole Hebrew Hindi Hungarian Icelandic Indonesian Irish Italian Japanese Korean Latvian Lithuanian Macedonian Malay Maltese Norwegian
Persian Polish Portuguese Romanian Russian Serbian Slovak Slovenian Spanish Swahili Swedish Thai Turkish Ukrainian Urdu Vietnamese Welsh Yiddish Bengali Bosnian
Cebuano Esperanto Gujarati Hausa Hmong Igbo Javanese Kannada Khmer Lao Latin Maori Marathi Mongolian Nepali Punjabi Somali Tamil Telugu Yoruba
Zulu
Английский Французский Немецкий Итальянский Португальский Русский Испанский