powered by simpleCommunicator - 2.0.60     © 2026 Programmizd 02
Целевая тема:
Создать новую тему:
Автор:
Закрыть
Цитировать
Форумы / Visual Basic [игнор отключен] [закрыт для гостей] / Поиск по различным полям таблицы БД в ADO
23 сообщений из 23, страница 1 из 1
Поиск по различным полям таблицы БД в ADO
    #32670169
Radist
Скрыть профиль Поместить в игнор-лист Сообщения автора в теме
Участник
Раньше, при работе в DAO я использовал для многокритериального поиска в таблице базы по разным полям запрос:

strSQL = "SELECT * FROM Components WHERE Components.Model Like " & "'*" & Text7.Text & "*'" & Two & Tri & Chet & Second

Переменные Two, Tri, Chet, Second формируются аналогично с помощью Like.

Можно ли производить такой же многокритериальный поиск по различным полям при использовании ADO.

Ну, например, так (не работает):

sCriteria = "Model Like " & "'*" & Text7.Text & "*'" & Two & Tri & Chet & Second & "order by Name"
adors.Find sCriteria, adSearchForward

или по другому? У меня в ADO ничего не получается. Помогите!
...
Рейтинг: 0 / 0
Поиск по различным полям таблицы БД в ADO
    #32670252
МаксимВ
Скрыть профиль Поместить в игнор-лист Сообщения автора в теме
Участник
Я тебе кусок из своего приложения выдернул.

Код: plaintext
1.
2.
3.
4.
5.
6.
7.
8.
9.
10.
11.
12.
13.
14.
15.
16.
17.
18.
19.
20.
21.
22.
23.
24.
25.
26.
27.
28.
29.
30.
31.
32.
33.
34.
35.
36.
37.
 '*** ActiveX Control Event *** 
Private Sub cmdSeach_Click()
Dim strSample As String, i As Integer
Dim strMsg As String, Style, strTitle As String, Response As Integer
    
    strSample = RTrim$(frmExplorer.adoDB.Recordset.Fields( 3 ).Name) + " LIKE '%" + Me.cboSample.Text + "%'"
     ' Задаем значения переменных для MsgBox 
    strMsg = "Не удается найти " + Chr( 34 ) + Me.cboSample.Text + Chr( 34 )
    Style = vbOKOnly + vbInformation + vbDefaultButton1
    strTitle = "Поиск"
    If Me.chkStartBeginning.Value =  1  Then           ' поиск с начала 
        frmExplorer.adoDB.Recordset.Find strSample, , adSearchForward,  1 
        If frmExplorer.adoDB.Recordset.EOF Then      ' нет записей, удовлетворяющих условию 
            Response = MsgBox(strMsg, Style, strTitle)
        Else                                         ' поиск успешный 
            For i =  1  To frmExplorer.TreMain.Nodes.Count
                If Trim$(frmExplorer.TreMain.Nodes(i).Key) = Trim(frmExplorer.adoDB.Recordset( 0 )) + "_" Then
                    frmExplorer.TreMain.Nodes(i).Selected = True
                    Exit For
                End If
            Next i
            Me.chkStartBeginning.Value =  0 
        End If
    Else                                             ' продолжение поиска или поиск не сначала 
        frmExplorer.adoDB.Recordset.Find strSample,  1 , adSearchForward
        If frmExplorer.adoDB.Recordset.EOF Then      ' нет записей, удовлетворяющих условию 
            Response = MsgBox(strMsg, Style, strTitle)
        Else                                         ' поиск успешный 
            For i =  1  To frmExplorer.TreMain.Nodes.Count
                If Trim$(frmExplorer.TreMain.Nodes(i).Key) = Trim$(frmExplorer.adoDB.Recordset( 0 )) + "_" Then
                    frmExplorer.TreMain.Nodes(i).Selected = True
                    Exit For
                End If
            Next i
        End If
    End If

End Sub
...
Рейтинг: 0 / 0
Поиск по различным полям таблицы БД в ADO
    #32670953
Radist
Скрыть профиль Поместить в игнор-лист Сообщения автора в теме
Участник
Спасибо, Максим!

Буду разбираться.
...
Рейтинг: 0 / 0
Поиск по различным полям таблицы БД в ADO
    #32671030
Radist
Скрыть профиль Поместить в игнор-лист Сообщения автора в теме
Участник
Максим!
Насколько я понял, поиск идет все-таки по одному параметру
cboSample.Text ?
...
Рейтинг: 0 / 0
Поиск по различным полям таблицы БД в ADO
    #32671078
Radist
Скрыть профиль Поместить в игнор-лист Сообщения автора в теме
Участник
Мне надо производить одновременный многокритериальный поиск в таблице по различным полям (Model, Autor, KeyWord и т.д.). Переменные определяются вводимым при поиске содержимым текстовых полей:

Two = " AND Autor LIKE " & "'*" & Text8.Text & "*'"
If Text8.Text = Empty Then Two = Empty
If Check2.Value = 0 Then Two = Empty

Tri = " AND KeyWord LIKE " & "'*" & Text9.Text & "*'"
If Text9.Text = Empty Then Tri = Empty
If Check3.Value = 0 Then Tri = Empty

Chet = " AND KeyWord LIKE " & "'*" & Text10.Text & "*'"
If Text9.Text = Empty Then Chet = Empty
If Check4.Value = 0 Then Chet = Empty

Second = " AND Firm LIKE " & "'*" & Combo1.Text & "*'"
If Combo1.Text = Empty Then Second = Empty
If Check5.Value = 0 Then Second = Empty

В DAO это у меня работает, в ADO - нет!
А как сделать, пока нигде не нашел
...
Рейтинг: 0 / 0
Поиск по различным полям таблицы БД в ADO
    #32671143
marvan
Скрыть профиль Поместить в игнор-лист Сообщения автора в теме
Участник
используй % вместо *
EX: AND Autor LIKE " & "'%" & Text8.Text & "%'"
...
Рейтинг: 0 / 0
Поиск по различным полям таблицы БД в ADO
    #32671329
МаксимВ
Скрыть профиль Поместить в игнор-лист Сообщения автора в теме
Участник
cboSample.Text содержит следующее:
Код: plaintext
cboSample.Text="английское название поля"+"LIKE '%"+"искомое значение%' "
Это я ищу по одному полю(мне больше не надо). Сделай так:
Код: plaintext
cboSample.Text="английское название поля1"+"LIKE '%"+"искомое значение1%' "+" and "+"английское название поля2"+"LIKE '%"+"искомое значение2%' "
...
Рейтинг: 0 / 0
Поиск по различным полям таблицы БД в ADO
    #32675824
Radist
Скрыть профиль Поместить в игнор-лист Сообщения автора в теме
Участник
Нет, что-то у меня ничего не катит :(.
Перепробовал разные варианты, например:
sCriteria = "Name Like '%" + "as%' " '+ "Autor Like '%" + "ar%' " ' & Text2.Text & "%'" '& "Autor Like " & "'%" & Text1.Text & "%'"

sCriteria = "Name Like " & "'*" & Text2.Text & "*'" '& "Autor Like " & "'*" & Text1.Text & "*'"

adors.MoveFirst

While adors.EOF = False
adors.Find sCriteria, adSearchForward
List2.AddItem adors.Fields("Name")
adors.MoveNext
Wend

По одному полю ищет без проблем. Как только добавляю поск по другому полю - перестает искать совсем. Выдает все записи.

Может что-нибудь подскажете?
...
Рейтинг: 0 / 0
Поиск по различным полям таблицы БД в ADO
    #32675875
Фотография Magnus23
Скрыть профиль Поместить в игнор-лист Сообщения автора в теме
Участник
К чему конекимся? Сиквел?
В последнем варианте между параметрами должно быть AND, теретически :).

Выкинь содержимое строки поиска после формирования.

Magnus
...
Рейтинг: 0 / 0
Поиск по различным полям таблицы БД в ADO
    #32676247
МаксимВ
Скрыть профиль Поместить в игнор-лист Сообщения автора в теме
Участник
Должно быть так(работает и в Access и MSSQL):
Код: plaintext
sCriteria = "Name Like '%" & Text2.Text & "%' & " AND " & "Autor Like '%" & Text1.Text & "%'"

Magnus32: ты где пропадал?
...
Рейтинг: 0 / 0
Поиск по различным полям таблицы БД в ADO
    #32676273
МаксимВ
Скрыть профиль Поместить в игнор-лист Сообщения автора в теме
Участник
Пардон, одни "кавычки" пропустил. Да, и Access 2000.
Код: plaintext
sCriteria = "Name Like '%" & Text2.Text & "%'" & " AND " & "Autor Like '%" & Text1.Text & "%'"
...
Рейтинг: 0 / 0
Поиск по различным полям таблицы БД в ADO
    #32676313
(c)VIG
Скрыть профиль Поместить в игнор-лист Сообщения автора в теме
Участник
О чем шумим ,братцы?
Find в ADO работет только с одним полем. Для поиска по нескольким полям надо использовать метод Filter
...
Рейтинг: 0 / 0
Поиск по различным полям таблицы БД в ADO
    #32676350
Фотография Magnus23
Скрыть профиль Поместить в игнор-лист Сообщения автора в теме
Участник
МаксимВДолжно быть так(работает и в Access и MSSQL):
Код: plaintext
sCriteria = "Name Like '%" & Text2.Text & "%' & " AND " & "Autor Like '%" & Text1.Text & "%'"

Magnus32: ты где пропадал?

На работе собсно :), новый проэкт, голову некогда поднять.


Вот пришел (c)VIG и испортил весь поспитательный процесс :).
Низя так сразу.
...
Рейтинг: 0 / 0
Поиск по различным полям таблицы БД в ADO
    #32676401
(c)VIG
Скрыть профиль Поместить в игнор-лист Сообщения автора в теме
Участник
авторВот пришел (c)VIG и испортил весь поспитательный процесс :).
Низя так сразу.
Платон мне друг, но истина дороже! (не мое)
...
Рейтинг: 0 / 0
Поиск по различным полям таблицы БД в ADO
    #32676862
Radist
Скрыть профиль Поместить в игнор-лист Сообщения автора в теме
Участник
Спасибо всем!
Сегодня - завтра некогда прог-ить - совещаемся с заказчиками.
Но, видимо, (c)VIG прав?

Все это работает в DAO. A в ADO облом!
Буду разбираться
...
Рейтинг: 0 / 0
Поиск по различным полям таблицы БД в ADO
    #32677476
(c)VIG
Скрыть профиль Поместить в игнор-лист Сообщения автора в теме
Участник
авторНо, видимо, (c)VIG прав?
Не "видимо" ,а абсолютно :)

Find Method
Searches a Recordset for the row that satisfies the specified criteria. Optionally, the direction of the search, starting row, and offset from the starting row may be specified. If the criteria is met, the current row position is set on the found record; otherwise, the position is set to the end (or start) of the Recordset.

Syntax
Find (Criteria, SkipRows, SearchDirection, Start)
Parameters
Criteria
A String value that contains a statement specifying the column name, comparison operator, and value to use in the search.
SkipRows
Optional. A Long value, whose default value is zero, that specifies the row offset from the current row or Start bookmark to begin the search. By default, the search will start on the current row.
SearchDirection
Optional. A SearchDirectionEnum value that specifies whether the search should begin on the current row or the next available row in the direction of the search. An unsuccessful search stops at the end of the Recordset if the value is adSearchForward. An unsuccessful search stops at the start of the Recordset if the value is adSearchBackward.
Start
Optional. A Variant bookmark that functions as the starting position for the search.
Remarks
Only a single-column name may be specified in criteria. This method does not support multi-column searches .

The comparison operator in Criteria may be ">" (greater than), "<" (less than), "=" (equal), ">=" (greater than or equal), "<=" (less than or equal), "<>" (not equal), or "like" (pattern matching).

The value in Criteria may be a string, floating-point number, or date. String values are delimited with single quotes or "#" (number sign) marks (for example, "state = 'WA'" or "state = #WA#"). Date values are delimited with "#" (number sign) marks (for example, "start_date > #7/22/97#").

If the comparison operator is "like", the string value may contain an asterisk (*) to find one or more occurrences of any character or substring. For example, "state like 'M*'" matches Maine and Massachusetts. You can also use leading and trailing asterisks to find a substring contained within the values. For example, "state like '*as*'" matches Alaska, Arkansas, and Massachusetts
Asterisks can be used only at the end of a criteria string, or together at both the beginning and end of a criteria string, as shown above. You cannot use the asterisk as a leading wildcard ('*str'), or embedded wildcard ('s*r'). This will cause an error..


Note An error will occur if a current row position is not set before calling Find. Any method that sets row position, such as MoveFirst, should be called before calling Find.
...
Рейтинг: 0 / 0
Поиск по различным полям таблицы БД в ADO
    #32677555
Radist
Скрыть профиль Поместить в игнор-лист Сообщения автора в теме
Участник
(c)VIG[quot автор]Но, видимо, (c)VIG прав?
Не "видимо" ,а абсолютно :)

[quot ][quot]
Спасибо, прочувствовал. Наскороту попробовал метод Filter - тоже не пропер по второму полю.
Но эксперементировать некогда - лужу усеченную однокритериальную версию, чтобы в понедельник показать заказчику. Хотя вся прелесть программы исчезает.
...
Рейтинг: 0 / 0
Поиск по различным полям таблицы БД в ADO
    #32677584
(c)VIG
Скрыть профиль Поместить в игнор-лист Сообщения автора в теме
Участник
Мне что ,весь хелп скопировать? :)
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.

Only Filters in the form of Criteria Strings (e.g. OrderDate > '12/31/1999') affect the contents of a persisted Recordset. Filters created with an Array of Bookmarks or using a value from the FilterGroupEnum will not affect the contents of the persisted Recordset. These rules apply to Recordsets created with either client-side or server-side cursors.
...
Рейтинг: 0 / 0
Поиск по различным полям таблицы БД в ADO
    #32677640
Radist
Скрыть профиль Поместить в игнор-лист Сообщения автора в теме
Участник
(c)VIG!

Ну, не ругайся ты!
Поясню ситуацию. Я не проф. программист. Начинал с VB1-DOS. Лужу чисто прикладные свои (связные) задачки. Основная моя работа - оборудование мобильной связи.
Перешел постепенно на VB6 (Поднялся :)). Пользуюсь парой книг по Access и VB6(Программирование БД).
Пока хватало. А Help, который ты дерешь, я даже не знаю откуда.
Ты уж извини за напряг.

Спасибо, успехов!
...
Рейтинг: 0 / 0
Поиск по различным полям таблицы БД в ADO
    #32677766
(c)VIG
Скрыть профиль Поместить в игнор-лист Сообщения автора в теме
Участник
Radist(c)VIG!
Ну, не ругайся ты!../quot]
Там вроде бы смайлик был
[quot автор]Help, который ты дерешь, я даже не знаю откуда.
Ну ,если на компьютере не установлен ,то можно
отсюда
Удачи!
...
Рейтинг: 0 / 0
Поиск по различным полям таблицы БД в ADO
    #32677822
Radist
Скрыть профиль Поместить в игнор-лист Сообщения автора в теме
Участник
Да, я когда купил VB6, там в пакете не было Helpa вообще. Так и юзаю с хелпом от VB4.
По поводу смайлика. Сижу слегка задрюченный от заморочек и недосыпов - не обратил внимания - извини!

Ну и маленькая история для разрядки в тему. Сын мне тут прислал SMS-ку.
"Как ты отнесешься к тому, что я приду домой, не такой как уходил?"
В свете последних событий я, получив ее чуть с ума не сошел. Звоню ему, а он говорит - "Ты что! Там же в конце я смайлик поставил!".

Спасибо за помощь! Лужу дальше.
...
Рейтинг: 0 / 0
Поиск по различным полям таблицы БД в ADO
    #32678984
VB Читатель
Скрыть профиль Поместить в игнор-лист Сообщения автора в теме
Гость
Радист?

Так что с сыном-то было?
...
Рейтинг: 0 / 0
Поиск по различным полям таблицы БД в ADO
    #32680841
Radist
Скрыть профиль Поместить в игнор-лист Сообщения автора в теме
Участник
Чего-чего?
Да покрасил волосы в блондинский цвет.
Вот чего.
...
Рейтинг: 0 / 0
23 сообщений из 23, страница 1 из 1
Форумы / Visual Basic [игнор отключен] [закрыт для гостей] / Поиск по различным полям таблицы БД в ADO
Найденые пользователи ...
Разблокировать пользователей ...
Читали форум (0):
Пользователи онлайн (0):
x
x
Закрыть


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