Top.Mail.Ru
Мастера DELPHI, Delphi programming community Титульная страница Поиск, карта сайта Написать письмо 
| Новости | Поиск | FAQ | Статьи | Книги | Новости VCL |
| Форумы ЧАТ | Орешник | KOL и MCK |
Форумы -» Основная («Начинающим»)/ Базы / WinAPI / Компоненты / Сети / Media / Игры / Corba и COM / KOL / FreePascal / .Net / Прочее / RSDN.ORG

« предыдущая ветвь | форум | следующая ветвь »

Поиск по базе. [D6, dBase, FoxPro]


Страницы:   1 2

widom ©   (2003-04-07 07:21:00) 

Нужно сделать поиск по базе данных, когда значение поля частично совпадает со строкой.
Например строка RAV. Он должен вывести поля со значением Drav и Ravik.
SQL запросы не предлагать.


Silver_   (2003-04-07 16:42:00) [21]


> Соловьев © (07.04.03 16:20)
> может OnFilterRecord?

мона и OnFilterRecord я пользую так устанавливаю
DataSet.Filtered:=True;

у какованить Едита ...EditOnChange(Sender: TObject);
DataSet.Filter:="<<MyField>> LIKE ""+TEdit(Sender).Text+"*"";

усё работает как часы :) просто и немудрено


Соловьев   (2003-04-07 16:20:00) [22]

может OnFilterRecord?


Silver_   (2003-04-07 16:17:00) [23]


> 2 sunrider (07.04.03 16:02)


и ты считаещь что
Locate("MyField","RAV",[loPartialKey, loKeyInsensitive]);
выдаст
Drav
Ravik

я уверен ты получишь Drav а до Ravik с локейтом не доберешься
потому что он позиционирует курсор на ПЕРВУЮ подходящую запись и никак не выдаст тебе более одной

> Вообще работает достаточно быстро

быстро не есть правильно :)

вопще в данном случае либо SQL либо фильтр


sunrider   (2003-04-07 16:02:00) [24]

Есть такая функция Locate для Table и Query
Table.Locate(<имя поля - string>,<значение-variant>,
[loCaseInsensitive,loPartialKey]); Два последних ключа, как раз для типа поиска - последний если нужно частичное совпадение.
Вообще работает достаточно быстро


Silver_   (2003-04-07 12:04:00) [25]


> Долго, но верно! :)

Верно не есть лучше

в данном случае фильтрация и есть быстрее, проще (смотри код), а значит лучше :)


Dim!S   (2003-04-07 11:44:00) [26]

Извиняюсь, что-то с инетом :)
см. самое нижнее


Dim!S   (2003-04-07 11:43:00) [27]

> alex_bredin
FindNearest не сработает, потому что берет с первого символа и с учетом регистра, а в задаче условия совсем другие

Разве указанный мною способ не подходит? Долго, но верно! :)
По-моему, это единственный способ... (см. условия и для TTable)


Dim!S   (2003-04-07 11:39:00) [28]

> alex_bredin
FindNearest не сработает, потомо что берет с первого символа и с учетом регистра, а в задаче условия совсем другие


Dim!S   (2003-04-07 11:39:00) [29]

> alex_bredin
FindNearest не сработает, потомо что берет с первого символа и с учетом регистра, а в задаче условия совсем другие

Только по моему способу, долго, но верно! :)


Соловьев   (2003-04-07 11:33:00) [30]

еще можно(наверное даже нужно) - OnFilterRecord.


Silver_   (2003-04-07 11:29:00) [31]


> widom (07.04.03 07:21)
> Нужно сделать поиск по базе данных, когда значение поля
> частично совпадает со строкой.
> Например строка RAV. Он должен вывести поля со значением
> Drav и Ravik.

> SQL запросы не предлагать.


ВСЁ - фильтрация какраз поможет
тока не поля а записи :)

потому как Find... тока позиционирует курсор куда надо а надо не одну запись а ВСЕ подходящие, по крайней мере из вопроса так следует :)


alex _bredin   (2003-04-07 11:14:00) [32]

если TTable, то TTable.FindNearest

Moves the cursor to the record that most closely matches a specified set of key values.

procedure FindNearest(const KeyValues: array of const);

Description

Call FindNearest to move the cursor to a specific record in a dataset or to the first record in the dataset that is greater than the values specified in the KeyValues parameter. KeyValues contains a comma-delimited array of field values, called a key. Each value in the key can be a literal, a variable, a NULL value, or nil. If the number of values passed in KeyValues is less than the number of columns in the index used for the search, the missing values are assumed to be null. In the statement below, the FindKey method is used to find the table row with the value ""Princess Island SCUBA" in the index field.

Table1.FindNearest(["Princess Island SCUBA"]);

For Paradox and dBASE tables, the key must always be an index, which can be specified in the IndexName property. If IndexName is empty, FindNearest uses the table’s primary index. Note that FindKey does not work with dBASE expression indexes. Use the GotoKey or GotoNearest method instead.

For SQL tables, the key may correspond to a specified index in IndexName, or to a list of field names in the IndexFieldNames property.

FindNearest positions the cursor either on a record that exactly matches the search criteria, or on the first record whose values are greater than those specified in the search criteria. If there are no records that match or exceed the specified criteria, FindNearest positions the cursor on the last record in the table. KeyExclusive affects the boundary conditions of ranges and will affect the record selected by FindNearest.


Silver_   (2003-04-07 11:01:00) [33]

используй

DataSet.Filter:="<<MyField>> LIKE "rav*"";
DataSet.Filtered:=True;


и в результате у тебеа останутся только нужные записи
после
DataSet.Filtered:=False;
в твоем распоряжении опять все записи
Дерзай

P.S. работает достаточно быстро


alex _bredin   (2003-04-07 10:57:00) [34]

FindNearest


Соловьев   (2003-04-07 10:53:00) [35]


> SQL запросы не предлагать.

почему?


Veles   (2003-04-07 10:40:00) [36]

Согласен...


Dim!S   (2003-04-07 08:26:00) [37]

>>Veles
Не пройдет, если регистр букв разный...
Дополни его AnsiUpperCase


Veles   (2003-04-07 07:57:00) [38]

Можно и так, если база небольшая...

procedure TForm8.Button2Click(Sender: TObject);
VAR
I: Integer;
K: String;
S: String;
M: String;
begin
Table2.First;
S := Edit1.Text;
begin
For I := 1 To Table2.RecordCount Do
begin
M := Table2Name.Value;
K := Copy(M, 1, Length(S));
if S <> K Then Table2.Next;
end;
if S = K then MessageDlg("


Dim!S   (2003-04-07 07:44:00) [39]

Методом перебора записей...

при обработке записей используй:
MatchStrings(AnsiUpperCase(fmDM.Table1.FieldByName("Krat_Name").Value), AnsiUpperCase("*" + str + "*"));


(функцию нашел в инете)
******************
function MatchStrings(source, pattern: String): Boolean;
var

pSource: Array [0..255] of Char;
pPattern: Array [0..255] of Char;


function MatchPattern(element, pattern: PChar): Boolean;


function IsPatternWild(pattern: PChar): Boolean;
var
t: Integer;
begin
Result := StrScan(pattern,"*") <> nil;
if not Result then Result := StrScan(pattern,"?") <> nil;
end;


begin
if 0 = StrComp(pattern,"*") then
Result := True
else if (element^ = Chr(0)) and (pattern^ <> Chr(0)) then
Result := False
else if element^ = Chr(0) then
Result := True
else begin
case pattern^ of
"*": if MatchPattern(element,@pattern[1]) then
Result := True
else
Result := MatchPattern(@element[1],pattern);
"?": Result := MatchPattern(@element[1],@pattern[1]);
else
if element^ = pattern^ then
Result := MatchPattern(@element[1],@pattern[1])
else
Result := False;
end;
end;
end;

begin

StrPCopy(pSource,source);
StrPCopy(pPattern,pattern);
Result := MatchPattern(pSource,pPattern);
end;
*****************


Страницы:   1 2

Наверх

Титульная страница Поиск, карта сайта Написать письмо