Текущий архив: 2005.03.20;
Скачать: CL | DM;
Вниз
Сообщение об изменениях в БД Найти похожие ветки
← →
samalex (2005-02-16 12:55) [0]Уважаемые знатоки.
У меня база MSSQL 7.0. Разные пользователи заводят данные.
Вопрос : как программе узнать, что в определенную таблицу внесены или изменены данные? Согласитесь, что проверять постоянно через запросы - это глупо и напряжно для сервера БД.
К примеру, в IB есть "POST_EVENT".
Заранее благодарен.
← →
Sergey13 © (2005-02-16 13:25) [1]> Согласитесь, что проверять постоянно через запросы - это глупо и напряжно для сервера БД.
Так соглашусь.
Согласитесь, что проверять когда надо через запросы - это глупо и напряжно для сервера БД.
Вполне оптимальный вариант.
← →
Sergey13 © (2005-02-16 13:26) [2]В смысле, проверять когда надо через запросы - это не глупо и не напряжно для сервера БД.
8-)
← →
first_aid (2005-02-16 13:33) [3]>К примеру, в IB есть "POST_EVENT".
Проверять в IB через пост евент тоже шоколада мало!
Можно попробовать проверять по таймеру, когда приложение какое то время (напимер 5 минут) находится в простое, только гденибудь надо пользователю подсказчку вывести что происходит обновление данных находится в простое.
Или после каждой операции вставки, редактирования, удаления, перечитывать данные.
Насколько я знаю у MSSQL нет аналогов евентов IB.
← →
Digitman © (2005-02-16 13:49) [4]
> samalex
для решения такого рода задач реализуют 3-хзвенную архитектуру распределенного СУБД-приложения, где в кач-ве диспетчера/арбитра выступает 2-е звено - AppServer
тонкие клиенты не взаимодействуют с СУБД-сервером напрямую, они регистрируются на АппСервере и ему же адресуют свои запросы
АппСервер фиксирует/анализирует запросы каждого из клиентов, стартует если нужно соотв.транзакции, транслирует запросы (в нужном виде) СУБД-серверу, получает рез-ты, возвращает их клиенту, в случае успешного подтверждения транзакции если нужно рассылает прочим клиентам нужные извещения, по получению которых эти клиенты могут смело обновлять свои НД, делая соотв.запросы к АппСерверу
← →
MOA © (2005-02-16 13:53) [5]Есть SQL Server 2000 Notification Services: http://www.microsoft.com/sql/ns/default.asp
Хотя, конечно, использовать его в целях сабжа как-то даже и неловко ;).
← →
samalex (2005-02-16 14:09) [6]Sergey13
у меня каждые 10 сек. проверка. Просто не хочется, чтобы сервак постоянно пыхтел и занимал процессорное время.
first_aid
У меня (и не только у меня) не одна программа в IB реализована через "POST_EVENT". Все здорово.
Digitman ©
А что-нибудь попроще? Я хотел посылать почтовое сообщение, но не настроена на SQL почтовая служба.
← →
Sergey13 © (2005-02-16 14:14) [7][6] samalex (16.02.05 14:09)
>у меня каждые 10 сек. проверка.
Если это надо, то ничего особенного. Но вот надо ли это? Шибко я сомневаюсь. Ты тут не первый бьешься за "автоматическое обновление". Еще никому, вроде, толком не удалось объяснить здесь - зачем?
← →
samalex (2005-02-16 14:24) [8]MOA ©
У меня SQL 7.0, а не 2000. К тому же, мне никто не разрешит ставить что-то новое на работающий сервер. Слишком крупные задачи крутятся на нем. Но все равно, спасибо, почитаю, интересно.
← →
Ega23 © (2005-02-16 17:50) [9]
xp_sendmail
Sends a message and a query result set attachment to the specified recipients.
Syntax
xp_sendmail {[@recipients =] "recipients [;...n]"}
[,[@message =] "message"]
[,[@query =] "query"]
[,[@attachments =] "attachments [;...n]"]
[,[@copy_recipients =] "copy_recipients [;...n]"
[,[@blind_copy_recipients =] "blind_copy_recipients [;...n]"
[,[@subject =] "subject"]
[,[@type =] "type"]
[,[@attach_results =] "attach_value"]
[,[@no_output =] "output_value"]
[,[@no_header =] "header_value"]
[,[@width =] width]
[,[@separator =] "separator"]
[,[@echo_error =] "echo_value"]
[,[@set_user =] "user"]
[,[@dbuse =] "database"]
Arguments
[@recipients =] "recipients [;...n]"
Is the semicolon-separated list of the recipients of the mail.
n
Is a placeholder indicating that more than one recipient, copy_recipient, or blind_copy_recipient can be specified.
[@message =] "message"
Is the message to be sent. message can be up to 8,000 bytes.
[@query =] "query"
Is a valid Microsoft® SQL Server™ query, the result of which is sent in mail. xp_sendmail uses a bound connection for the query parameter. The query connection made by SQL Mail is not blocked by locks held by the client that issues the xp_sendmail request. This makes xp_sendmail easier to use from within triggers. The query statement, however, cannot refer to the logical inserted and deleted tables that are only available within a trigger. query can be up to 8,000 bytes.
[@attachments =] "attachments [;...n]"
Is a semicolon-separated list of files to attach to the mail message.
[@copy_recipients =] "copy_recipients [;...n]"
Is the semicolon-separated list identifying the recipients of a copy of the mail (cc:"ing).
[@blind_copy_recipients =] "blind_copy_recipients [;...n]"
Is an optional semicolon-separated list identifying recipients of a blind copy of the mail (bcc:"ing).
[@subject =] "subject"
Is an optional parameter specifying the subject of the mail. If subject is not specified, SQL Server Message is the default.
[@type =] "type"
Is the input message type based on the MAPI mail definition:
IP[M | C].Vendorname.subclass
If type is NULL, message types beginning with IPM appear in the inbox of the mail client and are found or read by xp_findnextmsg. Message types beginning with IPC do not appear in the inbox of the mail client and must be found or read by setting the type parameter. The default is NULL.
For more information about using custom message types, see the Microsoft Windows NT Resource Kit or the Microsoft Mail Technical Reference, available separately.
[@attach_results =] "attach_value"
Is an optional parameter specifying the result set of a query should be sent in mail as an attached file instead of being appended to the mail. If attachments is not NULL and attach_results is true, the first file name in attachments is used as the file name for the results. If attachments is NULL, a file name is generated with a .txt extension. The default is FALSE, which means that the result set is appended to the message.
[@no_output =] "output_value"
Is an optional parameter that sends the mail but does not return any output to the client session that sent the mail. The default is FALSE, which means that the client session of SQL Server receives output.
[@no_header =] "header_value"
Is an optional parameter that sends the query results in mail but does not send column header information with the query results. The default is FALSE, which means that column header information is sent with the query results.
[@width =] width
Is an optional parameter setting the line width of the output text for a query. This parameter is identical to the /w parameter in the isql utility. For queries producing long output rows, use width with attach_results to send the output without line breaks in the middle of output lines. The default width is 80 characters.
[@separator =] "separator"
Is the column-separator string for each column of the result set. By default, the column-separator is a blank space. Use of a column-separator allows easier accessibility of the result set from spreadsheets and other applications. For example, use separator with attach_results to send files with comma-separated values.
[@echo_error =] "echo_value"
When true, causes SQL Mail to capture any server messages or DB-Library errors encountered while running the query and append them to the mail message rather than writing them to the error log. Also, a count of rows returned/rows affected is appended to the mail message.
← →
Ega23 © (2005-02-16 17:51) [10]
Note When echo_error is true, xp_sendmail returns a status of 0 (success) if the mail is successfully sent, even if DB-Library errors or messages are encountered or the query returns no results.
[@set_user =] "user"
Is the security context in which the query should be run. If user is not specified, the security context defaults to that of the user executing xp_sendmail.
[@dbuse =] "database"
Is the database context in which the query should be run. The default is NULL, which means the user is placed in the default database.
Return Code Values
0 (success) or 1 (failure)
Result Sets
xp_sendmail returns this message:
Mail sent.
Remarks
The SQL Mail session must be started prior to executing xp_sendmail. Sessions can be started either automatically or with xp_startmail. For more information about setting up a SQL Mail session automatically, see Configuring Mail Profiles. One SQL Mail session supports all users on the SQL Server, but only one user at a time can send a message. Other users sending mail messages automatically wait their turns until the first user"s message is sent.
If query is specified, xp_sendmail logs in to SQL Server as a client and executes the specified query. SQL Mail makes a separate connection to SQL Server; it does not share the same connection as the original client connection issuing xp_sendmail.
Note query can be blocked by a lock held by the client connection issued xp_sendmail. For example, if you are updating a table within a transaction and you create a trigger for update that attempts to select the same updated row information as the query parameter, the SQL Mail connection is blocked by the exclusive lock held on row by the initial client connection.
xp_sendmail runs in SQL Server"s security context, which is a local administrator account by default. A valid user of xp_sendmail can access files for attachment to a mail message in an administrator"s security context. If nonsystem administrator users must access xp_sendmail and you want to guard against unsecured access to attachment files, the system administrator can create a stored procedure that calls xp_sendmail and provides the needed functionality but does not expose the attachments parameter. This stored procedure must be defined in the master database. The system administrator then grants execute permission on the stored procedure to the necessary users without granting permission to the underlying xp_sendmail procedure.
xp_sendmail sends a message and a query result set or an attachment to specified recipients, and uses a bound connection for the query parameter. The query connection made by SQL Mail is not blocked by locks held by the client that issues the xp_sendmail request. This makes xp_sendmail easier to use from within triggers. The query statement, however, cannot refer to the logical inserted and deleted tables that are only available within a trigger.
Note An access violation can result from an attempt to execute xp_sendmail when the post office and address book are on a file share that the MSSQLServer service cannot access due to inadequate permissions.
For more information about using a stored procedure for calling xp_sendmail, see How to use SQL Mail (Transact-SQL).
Permissions
Execute permissions for xp_sendmail default to members of the db_owner fixed database role in the master database and members of the sysadmin fixed server role, but can be granted to other users.
Examples
A. Use xp_sendmail with no variables
This example sends a message to user Robert King (e-mail is robertk) that the master database is full.
EXEC xp_sendmail "robertk", "The master database is full."
B. Use xp_sendmail with variables
This example sends the message to users Robert King and Laura Callahan (e-mail is laurac), with copies sent to Anne Dodsworth (e-mail is anned) and Michael Suyama (e-mail is michaels). It also specifies a subject line for the message.
EXEC xp_sendmail @recipients = "robertk;laurac",
@message = "The master database is full.",
@copy_recipients = "anned;michaels",
@subject = "Master Database Status"
C. Send results
This example sends the results of the sp_configure to Robert King.
EXEC xp_sendmail "robertk", @query = "sp_configure"
D. Send results as an attached file
This example sends the results of the query SELECT * FROM INFORMATION_SCHEMA.TABLES as a text file attachment to Robert King. It includes a subject line for the mail and a message that will appear before the attachment. The @width parameter is used to prevent line breaks in the output lines.
EXEC xp_sendmail @recipients = "robertk",
@query = "SELECT * FROM INFORMATION_SCHEMA.TABLES",
@subject = "SQL Server Report",
@message = "The contents of INFORMATION_SCHEMA.TABLES:",
@attach_results = "TRUE", @width = 250
E. Send messages longer than 7,990 characters
This example shows how to send a message longer than 7,990 characters. Because message is limited to the length of a varchar (less row overhead, as are all stored procedure parameters), this example writes the long message into a global temporary table consisting of a single text column. The contents of this temporary table are then sent in mail using the @query parameter.
CREATE TABLE ##texttab (c1 text)
INSERT ##texttab values ("Put your long message here.")
DECLARE @cmd varchar(56)
SET @cmd = "SELECT c1 FROM ##texttab"
EXEC master.dbo.xp_sendmail "robertk",
@query = @cmd, @no_header= "TRUE"
DROP TABLE ##texttab
See Also
sp_processmail
System Stored Procedures (SQL Mail Extended Procedures)
xp_deletemail
xp_findnextmsg
xp_readmail
xp_startmail
xp_stopmail
?
← →
Arazel © (2005-02-16 22:00) [11]А как сделать на DELPHI с ADOQuery1
Чтобы было так
Шагая по первой таблицы (DBGrid1)
а по первой табли и ключу или там индекса
показывалась во второй таблицы (DBGrid2)
Подскажите пожалуста?
← →
ЮЮ © (2005-02-17 03:49) [12]>Arazel © (16.02.05 22:00) [11]
Совершенно непонятно, как данная ветка могла сподвигнуть на подовный вопрос? :) Свои вопросы надо оформлять как вопрос, а не цепляться к чужой ветке !!!
← →
Anatoly Podgoretsky © (2005-02-17 07:46) [13]Arazel © (16.02.05 22:00) [11]
Хватит спамить
← →
Anatoly Podgoretsky © (2005-02-17 07:47) [14]ЮЮ © (17.02.05 03:49) [12]
http://delphimaster.net/view/3-1108557114/
← →
Digitman © (2005-02-17 08:29) [15]
> Ega23 © (16.02.05 17:50) [9]
стоило ли целый талмут здесь цитировать ?)
ты упустил самое важное - вся эта петрушка гроша ломаного не стоит, потому что логика ее - "бежать вперед паровоза" : клиент, сделавший модифицирующий запрос, еще не подтвердил транзакцию (и волен ее откатить, тем самым отменив проделанные им изменения), а почта с извещением о якобы достоверности изменений уже ушла другим заинтересованным клиентам)
← →
Ega23 © (2005-02-17 09:43) [16]2 Digitman © (17.02.05 08:29) [15]
А кто мешает ему ПОСЛЕ транзакции мэйлы рассылать? Если она удачно прошла.
А вообще всё в корне неправильно. Не так клиент-сервер надо делать...
← →
samalex (2005-02-17 11:40) [17]Ega23 ©
Спасибо за совет. Я уже думал об использовании почты под SQL, но неприятность в том, что она не настроена и никто мне настраивать ее не даст, слишком крупные задачи катаются на серваке.
Я реализовал свою задачу по-другому.
http://delphiworld.narod.ru/base/mssql_callback.html
Вроде, работает, когда посылаешь извещение отдельному клиенту. Всем не работает. Еще на сервере рождаются какие-то процессы, которые,
во-первых, посылают сообщение с новых портов,
во-вторых, блокируют Dll и не дают ее перезаписать ...
Если кто что посоветует, буду признателен ...
← →
Sergey13 © (2005-02-17 11:43) [18]2[17] samalex (17.02.05 11:40)
>слишком крупные задачи катаются на серваке.
>Если кто что посоветует, буду признателен ...
Плюнь на это, пока те крупняки еще крутятся. А то крутиться перестанут, налетишь по крупному. 8-)
← →
samalex (2005-02-17 11:59) [19]Sergey13 ©
Когда будешь работать с крупными базами (как у меня 5.5 Гб), заговоришь по другому ...
← →
Sergey13 © (2005-02-17 12:00) [20][19] samalex (17.02.05 11:59)
Именно поэтому и говорю именно так.
← →
Ega23 © (2005-02-17 12:01) [21]Когда будешь работать с крупными базами (как у меня 5.5 Гб), заговоришь по другому ...
И какая разница - крупная база или мелкая? Если грамотно идеология разработана, то извращаться ни там ни там не придётся.
А извратиться можно и на базе в 5 табличек по 100 записей в каждой...
← →
Danilka © (2005-02-17 12:02) [22][17] samalex (17.02.05 11:40)
> Если кто что посоветует, буду признателен ...
Полное отсутствие автообновлений + кнопка "Обновить". Достаточно для 99.99% систем, начиная от мелких и заканчивая системами маштаба предприятия. Мне не веришь - спроси у тех людей, которые писали "слишком крупные задачи", "катающиеся" у вас на сервере.
← →
samalex (2005-02-17 12:14) [23]Ega23 ©
Я признателен за ценные советы по проектированию баз. Но только проектированием нашего SQL занимались другие люди, я пишу под него отдельные задачи, сам я предпочитаю Firebird?, еще я задал вопрос под № 17.
Отдельно, я не разу не конфигурил почту под SQL, чтобы использовать xp_sendmail. Это сложный процесс?
← →
Ega23 © (2005-02-17 12:16) [24]Согласен с Danilka © (17.02.05 12:02) [22]
← →
Ega23 © (2005-02-17 12:18) [25]Отдельно, я не разу не конфигурил почту под SQL, чтобы использовать xp_sendmail. Это сложный процесс?
Я тоже никогда её не конфигурил, поэтому ответить не могу. Но то, что такая системная ХП существует - знаю.
По-поводу блокировки DLL - наверное, во время попытки перезаписи её кто-то использует. Останови всех клиентов данной DLL.
← →
Danilka © (2005-02-17 12:56) [26][23] samalex (17.02.05 12:14)
> Но только проектированием нашего SQL занимались другие люди,
> я пишу под него отдельные задачи
Просто интересно, те задачи, которые писал не ты, там есть автообновление, или нет?
← →
samalex (2005-02-17 13:32) [27]Danilka ©
Используют вовсю, только под IB.
По поводу необходимости, я пишу программу вывода аварийных ситуаций, и она должна отображать на экране сообщение сразу, а не ждать нажатия клавиши.
Eda23
xp_sendmail. Ты мне про эту процедуру полный хелп скинул!!! Я бы ее реализовал, но у меня SQL mail не работает ...
← →
Ega23 © (2005-02-17 13:48) [28]По поводу необходимости, я пишу программу вывода аварийных ситуаций, и она должна отображать на экране сообщение сразу, а не ждать нажатия клавиши.
Так бы сразу и сказал.
Создавай отдельный поток и внём пингуй сервер по таймеру. Как только аварийная ситуация - делай свои необходимые действия.
← →
Danilka © (2005-02-17 14:01) [29][27] samalex (17.02.05 13:32)
> Используют вовсю, только под IB.
Да я, вобщем-то, имел ввиду те "крупные задачи", что "катаются на серваке".
> По поводу необходимости
Дык, с этого и надо было начинать, а то сложилось впечатление, что у тебя во всех гридах юзерских автообновление. :)
← →
Ega23 © (2005-02-17 14:04) [30]что у тебя во всех гридах юзерских автообновление. :)
Во-во! Я тоже так подумал...
Страницы: 1 вся ветка
Текущий архив: 2005.03.20;
Скачать: CL | DM;
Память: 0.56 MB
Время: 0.06 c