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

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

доступ к результатам запроса [D7, MSSQL]


Страницы:   1 2 3 4

777 ©   (2005-07-26 10:34:00) 

Проблема следующая. Надо результат запроса к одной из БД записать (а потом дополнить) данными из другой БД. Для этого во второй БД создается таблица. Потом результат запроса к 1-ой базе (ADOQuery1) пытаюсь затолкать во вторую:
ADOQuery1.Open;
for Index := 1 to ADOQuery1.RecordCount do
 begin
   QueryText := QueryText + 'INSERT INTO TempTable (ProviderID, Name, Characteristics, ProviderPrice, Presence) VALUES (''' + ADOQuery1.DataSource.DataSet.FieldByName('Code').Value + ''', ''' + ADOQuery1.DataSource.DataSet.FieldByName('Name').Value + ''', ''' + ADOQuery1.DataSource.DataSet.FieldByName('Characteristics').Value + ''', ' + StringReplace(FloatToStr(ADOQuery1.DataSource.DataSet.FieldByName('Price').Value), ',', '.', []) + ', ''' + ADOQuery1.DataSource.DataSet.FieldByName('Presence').Value + ''') ';
   ADOQuery1.Next
 end;
ADOQuery2.SQL.Text := QueryText;
ADOQuery2.ExecSQL
Так вот проблем возникает на 3-ей строке, когда пытаюсь QueryText присвоить некоторые значение из ADOQuery1. По отладке видно, что DataSource у него Nil. Что делать?
PS однако сам результат запроса в Query1 прекрасно отображается в гриде, если грид настроить на Query1


msguns   (2005-07-26 11:15:00) [61]

Приведенная выше справка - из TADOQuery

Теперь читаем о "дедушке" (TDataSet):

Represents the data source of another dataset that supplies values to the dataset.

property DataSource: TDataSource;

Description

As implemented in TDataSet, the DataSource property is always nil.

Descendant dataset classes that support specifying a data source redeclare and implement methods for getting and setting the DataSource property


Ну и где ж тут собачка закопалась ? В смысле связь с [4]


msguns   (2005-07-26 11:11:00) [62]

>Ega23 ©   (26.07.05 11:06) [4]
>Это только одно из применений.
Основное- TDataLink.DataSource.DataSet.

Поясни для особо тупых.

Читаем справку:
Specifies the data source component from which to extract current field values to use in same-name parameters in the ADO query’s SQL statement.

property DataSource: TDataSource;

Description

Set DataSource to automatically fill parameters in a query with fields values from another dataset. Parameters that have the same name as fields in the other dataset are filled with the field values. Parameters with names that are not the same as fields in the other dataset do not automatically get values, and must be programmatically set. For example, if the SQL property of the TADOQuery contains the SQL statement below and the dataset referenced through DataSource has a CustNo field, the value from the current record in that other dataset is used in the CustNo parameter:

SELECT *

FROM Orders O

WHERE (O.CustNo = :CustNo)

DataSource must point to a TDataSource component linked to another dataset component; it cannot point to this query component. The dataset specified in DataSource must be created, populated, and opened before attempting to bind parameters. Parameters are bound by setting the ADO query’s Prepared property to True prior to executing the query. If the SQL statement used by a query does not contain parameters, or all parameters are bound by the application using the Parameters property or the ParamByName method, DataSource need not be assigned. The example below shows setting the DataSource property of ADOQuery2 to the data source for ADOQuery1, preparing ADOQuery2, and activating ADOQuery2:

with ADOQuery2 do begin

 DataSource := DataSource1;
 Prepared := True;
 Open;

end;


В простонародье такая привязка именуется Master-Detail


msguns   (2005-07-26 11:06:00) [63]

Если уж так надо заполнять TEMPTABLE именно в цикле через открытый запрос к 1-й базе (while not Eof do .. Next ..), то зачем добавлять запросами ? Не проще ли добавление делать методами самого датасета, например AppendRecord ?


Ega23   (2005-07-26 11:06:00) [64]

2 msguns ©   (26.07.05 11:01) [3]
Св-во DataSet.DataSource служит для связки датасета с главным НД в линковках типа Master-Detail и к сабжу никакого отношения не имеет.

Это только одно из применений. Основное - TDataLink.DataSource.DataSet. А потомки TDataLink есть у каждого DB-компонента


msguns   (2005-07-26 11:01:00) [65]

Св-во DataSet.DataSource служит для связки датасета с главным НД в линковках типа Master-Detail и к сабжу никакого отношения не имеет.

Попутно вопрос:
А зачем так вычурно, нельзя ли во временную таблицу вставлять из ADOQuery1 непосредственно запросом ?
Т.е. заменить SQL в ADOQuery1 с SELECT FROM TABLE1 на
INSERT INTO TEMPTABLE .. SELECT FROM TABLE1

?


777   (2005-07-26 10:40:00) [66]

Просто я не знал, что у ADOQuery есть метод FieldByName, т.е. я думал, что он доступен толькочерез DataSourse.DataSet
Спасибо! Сейчас попробую


Lexer   (2005-07-26 10:37:00) [67]

А зачем ты обращаешься к ADOQuery1.DataSource, я так понял тебе надо к самому ADOQuery1, тогда так:
ADOQuery1..FieldByName(.....).Value


Страницы:   1 2 3 4

Наверх

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