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

Вниз

Добавление записей в связанные таблицы на ADO   Найти похожие ветки 

 
Макс   (2002-06-21 17:02) [0]

Уважаемые мэтры программирования БД помогите решить такую задачу

Имеется две таблицы Table1 и Table2. Table1 главная, Table2 подчиненная. Ключевое поле у Table1 identity
В компоненте ADOQuery соответственно запрос
select t1.Field_x, t1.Field_y, t2.Field_z
from Table1 t1, Table2 t2
where t1.PrimKeyField=t2.ForKeyField
всё замечательно и прекрасно работает

Но вот проблема при одновременной вставке в обе таблицы на сервер идет след. команда(отслежено с помощью Profiler)
insert Table1 (Fields1, Fields2, ...,Fieldsn) values (111, 222, ...,nnn)
select @@identity
insert Table2 (Fields1, Fields2, ...,Fieldsn, ForKeyField) values (111, 222, ...,nnn, null)

что естественно взывает отвал т.к. поле ForKeyField не м.б. null
так вот как грамотно в значение этого поля поместить значение identity ???
меня смущает select @@identity после первого insert Table1? не просто же так это делается...

Заранее всем спасибо


 
kig   (2002-06-21 17:29) [1]

Приверно так


BEGIN TRANSACTION
insert Table1 (Fields1, Fields2, ...,Fieldsn) values (111, 222, ...,nnn)
if @@error = 0
begin
insert Table2 (Fields1, Fields2, ...,Fieldsn, ForKeyField) values (111, 222, ...,nnn, @@identity)
COMMIT TRANSACTION
end
else ROLLBACK TRANSACTION



 
Макс   (2002-06-21 17:37) [2]

Это если команды прописывать вручную, то да всё замечательно

Я имел в виду, что когда вызывается метод ADOQuery.Post
(текст SQL запроса в ADOQuery приведен выше), при этом в поля занеслись новые значения то на сервер приложением идет набор команд, так же приведенный выше, я на эти команды никакого влияния не оказываю, их формирует приложение, так вот хотелось бы как то вмешаться.


 
kig   (2002-06-21 18:48) [3]

Если Вы используйте клиентский курсор, то возможно Вам поможет это:

Unique Table, Unique Schema, Unique Catalog Properties—Dynamic (ADO)
Enables you to closely control modifications to a particular base table in a Recordset that was formed by a JOIN operation on multiple base tables.

Unique Table specifies the name of the base table upon which updates, insertions, and deletions are allowed.
Unique Schema specifies the schema, or name of the owner of the table.
Unique Catalog specifies the catalog, or name of the database containing the table.
Settings and Return Values
Sets or returns a String value that is the name of a table, schema, or catalog.

Remarks
The desired base table is uniquely identified by its catalog, schema, and table names. When the Unique Table property is set, the values of the Unique Schema or Unique Catalog properties are used to find the base table. It is intended, but not required, that either or both the Unique Schema and Unique Catalog properties be set before the Unique Table property is set.

The primary key of the Unique Table is treated as the primary key of the entire Recordset. This is the key that is used for any method requiring a primary key.

While Unique Table is set, the Delete method affects only the named table. The AddNew, Resync, Update, and UpdateBatch methods affect any appropriate underlying base tables of the Recordset.

Unique Table must be specified before doing any custom resynchronizations. If Unique Table has not been specified, the Resync Command property will have no effect.

A run-time error results if a unique base table cannot be found.

These dynamic properties are all appended to the Recordset object Properties collection when the CursorLocation property is set to adUseClient.


 
Макс   (2002-06-23 00:40) [4]

Вобщем я думаю, что это то что надо, но к сожалению очень мало информации и с английским не совсем на "ты". Я так понимаю речь идет о ADOQuery.Properties. Если есть какие-нибудь ссылки и/или фаилы, то буду очень признателен. Тема очень специфичная и (по собственным наблюдениям) в литературе почему то её обходят стороной как првило пишут, что это выходит за рамки книги ....
:-(


 
Polevi   (2002-06-23 12:14) [5]

http://delphi.vitpc.com/helloworld/ado01.htm



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

Форум: "Базы";
Текущий архив: 2002.07.15;
Скачать: [xml.tar.bz2];

Наверх





Память: 0.46 MB
Время: 0.012 c
4-47871
Wizard_Ex
2002-05-10 12:33
2002.07.15
Немодальная форма и DLL =>


3-47092
VAleksey
2002-06-20 07:48
2002.07.15
Query.Open против ExecSQL


1-47510
Wolverin
2002-06-27 16:17
2002.07.15
ToolBar


1-47471
ValeX
2002-07-03 16:34
2002.07.15
мат. вопрос


1-47252
Skywalker
2002-06-27 12:13
2002.07.15
Алгоритм деления





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
Английский Французский Немецкий Итальянский Португальский Русский Испанский