Is it possible a trigger on a select statement with MySQL? - mysql

I know that triggers can be used on insert, update and delete, but what about a trigger (or sort of) on a select statement. I want to use a trigger to insert data on a table B when it is selected an existent record on a table A, it could be possible?.
Thanks in advance.

You should design your application so that database access occurs only through certain methods, and in those methods, add the monitoring you need.

Not exactly a trigger, but you can:
CREATE FUNCTION myFunc(...) BEGIN INSERT INTO myTable VALUES(...) END;
And then
SELECT myFunc(...), ... FROM otherTable WHERE id = 1;
Not an elegant solution, though.

It is not possible in the database itself.
However there are monitoring/instrumentation products for databases (e.g. for Sybase - not sure about MySQL) which track every query executed by the server, and can do anything based on that - usually store the query log into a data warehouse for later analysis, but they can just as well insert a record into table B for you, I would guess.

You can write an application which will be monitoring the query log and doing something when a select occurs. A pretty crude way to solve the problem though...

Related

Can I pass a value into a SQL trigger through a query?

I want to create a history table for actions done inside the database, the easiest way i thought was to create a history table that was updated through a trigger on each table modified.
I would like to also include a userId so I can identify who changed it as well, but when i do my inserts/delete statements etc, I would also need to add in the userId (which kinda has no relevance to the operation), in order to use the history table as i described.
So is there a way to just put the userId into a SQL statement? Or should I just actually do the history table as a separate query after doing my insert / delete statements, rather than using a trigger
Thanks in advance
Grant
It will be the best practices to add user column in main table which we can easily use in trigger to inserts/delete/update in history table.

mysql triggers using vs select query

I use mysql trigger to update column in one of ,y DB tables called comments_count but I want to know what is best and faster??
Using mysql triggers or select query like this below:
select count(*) from comments where discussion_id=something
different types of overhead:
with the trigger you will have extra time during insert, and may get out of synch over time for some unforseen reason.
with the query, you will always get the right answer but you will need to calculate at runtime. usually, this should be very fast especially with an index on the discussion_id

MySQL and implementing something close to sequences?

I am recently in the process of moving from oracle to mysql and would like some advice if how i am implementing something similar to sequences in mysql is a good way.
Essentially how i am currently going to implement it is by having a separate table in mysql for each sequence in oracle and have a single column which represents the last_number and increment this column when ever i insert a new row, that's one way another way i could go about doing it is by creating a single table with several rows representing each sequence and increment each row separately whenever i do an insert.
Another simpler way of doing it i could just do a select max()+1 on the relevant column when inserting data.
I'm basically thinking of switching to the select max()+1 option as it seems simpler to implement, but i would like to get some advice on what you think would be the best way of doing it out of these options, and if there is any pitfalls that i am currently not aware of when using select max()+1.
Also the reason im am not using auto_increment and the function last_insert_id() is i want to follow the ansi standard.
Thanks.
First of all: The max()+1 version is NOT guaranteed to give you a sequence, if you use transactions in a high isolation level.
The way we typically use sequences (if we can't avoid them) is to create a table with an AUTO_INCREMENT value, INSERT INTO it, SELECT last_insert_id(), DELETE FROM table WHERE field<$LASTINSERTID. This is ofcourse done in a stored procedure.
There is a read consistency problem, in that two sessions both running ...
insert into ... select max(..)+1 from ...
... at the same time both see the same value of max(...), hence they both try to insert the same new value.
You have the same problem with your table of maxima method, and you have to use a locking mechanism to avoid multiple session reading the same value. This leads to a concurrency problem where inserts to the table are serialised.

SQL Server : track table inserts

I have a table which get new data inserted every minute or so. According to the source code I have here, it is only done in one class which is not used anymore.
Is there any way to trace the inserts? What I mean is to see which queries they were inserted by, who sent those queries etc. As much info as possible.
I have tried several ways myself (e.g.sp_who2 'Active' stored procedure) without any success. I also have access to the machine running the SQL server and to the transaction backup files (.trn files) but have no idea how to open those files.
Add trigger to the table which follows inserts and insert to other table these variables:
getdate(),
host_name(),
App_Name(),
suser_sname()
Seems to me that this is enough
The trigger looks like this:
CREATE TRIGGER YourTrigger On YourTable
AFTER INSERT
AS
SET NOCOUNT ON;
INSERT logtable
SELECT APP_NAME(), HOST_NAME(), SUSER_SNAME(), GETDATE(), * FROM INSERTED
GO
OR
you can use Sql Server Profiler for catching the queries - it may be more flexible
You may use sp_depends like this:
sp_depends tablename
This only states information in the same database but it might say what you need!

Mysql Trigger Or just a simple Insert statement .. which one is better to log history?

I have so many tables in my DB.
eg. user, organisation,etc.
**User**
userId,name,age,orgId,etc..
**SessionLog**
logId, userId, operations, reason
If one admin makes changes like inserting, updating ,deleting, I will log every operations in SessionLog table WHAT he made.
So I plan to use Trigger.But the problem is I want to log the userId for WHO too. By using Trigger WHAT is OK. But for logging WHO, how can I do ?
1) do I need to retrieve the logId and need to update the row with WHO?
or
2) just use the simple INSERT statement to log everything? which way is better?
3) Is there any way to pass desired parameters to Trigger?
Thanks.
1. User
You can use CURRENT_USER to get this. http://dev.mysql.com/doc/refman/5.0/en/information-functions.html#function_current-user
2. Insert statement vs. Trigger
A trigger will abstract logging away from everybody else, and usually is the easiest solution that stays hidden.
INSERTS / UPDATES will not return until the trigger has completed.
Therefore while triggers on tables with light activity is an OK idea, it will become a real hindrance when dealing with tables that have a lot of activity.
Another option is to encapsulate this in the data access layer, but if you have even a single user that has direct access to the data (DBA included) then I do not recommend this approach.