Trigger when a select occurs - sql

i have a customer with a ERP wich i don't have programming access, and wants to do a special trigger when a item is selected. The problem is that the ItemID is nowhere kept when chosen, only when whole sale is kept, and the trigger should happen before that.
This is a novice question for sure, but this value must be kept somewhere right ?
When i do a audit do see what happens when the item is chosen inside the ERP it only does SELECT statments. Can i do a trigger based on a SELECT ?
Thank you.

It is not possible to create a trigger based on execution of a select query in PL/SQL. Trigger can be created only on INSERT, UPDATE or DELETE.
References :
https://community.oracle.com/thread/1556647?tstart=0
http://www.geekinterview.com/question_details/18571

Related

Trigger to ensure a value cannot happen

This is using Oracle SQL.
Apologies in advance as I am new to the SQL world.
I'm trying to create a simple trigger to ensure a sports event cannot happen in a certain month (we'll use December as the example). So if someone tries to insert a new row with a date in December, the trigger will prevent it.
The current table uses the DATE datatype, inserted as 'DD-MMM-YYYY' but when selected it's displayed as 'DD-MMM-YY' (I don't know why.)
Anyway, I've never made triggers before and I've tried it two ways but it bugs out because when I press ENTER on SQL Plus, it just keeps going as if I was missing a semi-colon. And I'm guessing the trigger itself is not working.
CREATE OR REPLACE TRIGGER event_test
BEFORE INSERT OR UPDATE
ON sports_event
BEGIN
IF DATE
IS 'DEC' THEN
'Sports cannot occur during December.';
END IF;
END;
I've also tried with a CASE and I could not get it to work.
I'm trying to create a simple trigger to ensure a sports event cannot happen in a certain month
[...]
The exercise that I'm trying to do this for specifically asks to create a trigger to ensure the event cannot happen in a certain month.
As this is for homework / educational purpose, here are some hints first:
First, as this was said by Mureink in his answer, remember that a CHECK CONSTRAINT is the preferred way to do data validation;
Then, as you are required to use a trigger, you will need both an INSERT trigger and an UPDATE trigger;
As you will do data validation, you need a BEFOREINSERT OR UPDATE trigger;
You will access to incoming data using the NEW. pseudo-record;
And you will reject DML statement by raising an exception.
You already have the (2) and (3) in your code. Starting from that, one complete solution might look like this:
CREATE OR REPLACE TRIGGER event_test
BEFORE INSERT OR UPDATE
ON sports_event
FOR EACH ROW WHEN (EXTRACT(MONTH FROM NEW.event_date) = 12)
BEGIN
RAISE_APPLICATION_ERROR (
num=> -20107,
msg=> 'Sports cannot occur during December.');
END;
Untested. Beware of typos !
Triggers aren't really meant for data validation. Why not use a check constraint instead?
ALTER TABLE sports_event
ADD CONSTRAINT not_in_december_ck
CHECK (TO_CHAR(event_date, 'MM') != '12')

SQL Server: DonĀ“t execute a Trigger when the updater is another trigger

Here is the scenario:
There is Trigger A and Trigger B, both in the Person table. I can't trigger the Trigger A when the update on table Person comes from Trigger B.
Is there something, such as an IF that I could use to solve this situation?
Thanks in advance for any help!
Right at the start, I will warn you that having multiple triggers on one table is not a good idea. Try and merge the actions of the two triggers into one if possible. However, if that is not a solution for you, then read on for my version. (I am not certain if it is practically valid, but go ahead and give it a shot anyway)
CREATE TRIGGER triggerB
ON yourtable
FOR UPDATE
AS
BEGIN
ALTER TABLE table_name DISABLE TRIGGER triggerA
--your processing
ALTER TABLE table_name ENABLE TRIGGER triggerA
END
This question deals with disabling then enabling triggers inside a stored procedure. This is an application of the same in a trigger.
Disclaimer: I am counting on this to fail because altering a table while in a trigger defined on that same table seems like an impossible task. But I have no resources at hand to test my wacky theory, so please test it and let me know if I'm thinking too far outside the box.
I got it!
IF TRIGGER_NESTLEVEL(OBJECT_ID('TRIGGER_NAME')) = 0
BEGIN
-- Your Trigger STuff
END
Thanks for answers and comments.

Is it possible to update trigger table in update trigger?

I have an update trigger for a table. When I am updating the table rows I need to check certain condition in trigger then based on that I want to update another column.
Is it possible?
You might want to read the documentation for CREATE TRIGGER, especially the remarks section, which includes:
If an INSTEAD OF trigger defined on a table executes a statement against the table that would ordinarily fire the INSTEAD OF trigger again, the trigger is not called recursively. Instead, the statement is processed as if the table had no INSTEAD OF trigger and starts the chain of constraint operations and AFTER trigger executions.
If this, or other parts of the remarks section, don't answer your questions, you probably need to add more to your question about what problems you're having, or what issues you're concerned about.

Should I use the template from MS SQL Management Studio to create new triggers?

If you create a new trigger in MS SQL Management Studio by using the GUI, it gives you this template:
--====================================
-- Create database trigger template
--====================================
USE <database_name, sysname, AdventureWorks>
GO
IF EXISTS(
SELECT *
FROM sys.triggers
WHERE name = N'<trigger_name, sysname, table_alter_drop_safety>'
AND parent_class_desc = N'DATABASE'
)
DROP TRIGGER <trigger_name, sysname, table_alter_drop_safety> ON DATABASE
GO
CREATE TRIGGER <trigger_name, sysname, table_alter_drop_safety> ON DATABASE
FOR <data_definition_statements, , DROP_TABLE, ALTER_TABLE>
AS
IF IS_MEMBER ('db_owner') = 0
BEGIN
PRINT 'You must ask your DBA to drop or alter tables!'
ROLLBACK TRANSACTION
END
GO
Should I use this template?
I dont know anything about triggers, but I think I need to use them. The purpose in this case is that on an insert to the table, I need to update one of the fields.
Please help me get started!
OK to begin with that is the wrong template if you want an ordinary trigger that one is a trigger on making structural changes to the table itself.
If you decide to do a trigger that affects data (as opposed to structure), there are several things you need to know. First and by far the most critical, triggers operate on sets of data not one row at time. You must write any trigger to handle multiple row inserts.updates or deletes. If you end up with any code setting the value in inserted or deleted to a variable, there is a 99% chance it will not work properly if multiple records are involved.
What is inserted or deleted you ask? That is the next thing you need to know about triggers, there are two pseudotables (inserted and deleted) that are only available in a trigger (or an output clause) which contain the new information being inserted or the updated values (in the inserted table) and the old information being deleted or being changed by an update (in the deleted table). So an insert has values in inserted, a delete has values in deleted and an update has values in both. Use these in your trigger to pull the values you need to change.
Since you don't know anything about triggers, I would say no, don't use the template.
Read the books online page for Create Trigger and write the trigger by hand.
There is probably more in that template code than you actually need. Read the manual and keep it simple.
If you don't know anything about triggers then I would strongly suggest that you read up on them before implementing them. Get Triggers right and they can make your life a lot easier; get it wrong and Triggers will cause you a lot of trouble.
I would suggest starting off with this tutorial
http://www.sqlteam.com/article/an-introduction-to-triggers-part-i
You can use the above SQL as a template or you can simply write your own. I would suggest you write your own as you'll understand what you are doing. Obviously only do this after you have done some serious reading on triggers. Check out MSDN too

SQL Server 2005 Insert Trigger with Update Statement

I am currently not in a location to test any of this out but would like to know if this is an option so I can start designing the solution in my head.
I would like to create an insert trigger on a table. In this insert trigger, I would like to get values from the inserted virtual table and use them to UPDATE the same table. Would this work or would we enter some kind of infinite loop (even though the trigger is not for update commands).
As an example if a row was inserted (which represents a new rate/cost for a vendor) I would like to update the same table to expire the old rate/cost for that vendor. The expiration is necessary vs updating the record that already exists so a history of rates/costs can be kept for reporting purposes (not to mention that the current reporting infrastructure expects this type of thing to happen and we are migrating current reports/data to SQL Server).
Thanks!
If you have only an INSERT trigger and no UPDATE trigger then there isn't any problem, but I assume you want to catch also UPDATEs and perhaps even DELETEs.
The INSTEAD OF triggers are guaranteed not to behave recursively:
If an INSTEAD OF trigger defined on a
table executes a statement against the
table that would ordinarily fire the
INSTEAD OF trigger again, the trigger
is not called recursively
With and INSTEAD OF trigger you must do both the original INSERT and the UPDATE you desire.
This doesn't sound like it would cause any problems to me, providing you're not doing an INSERT in another UPDATE trigger.