Refer to an other table's column in a trigger? - sqlite

Given:
CREATE TABLE worktags (
worktag_id integer not null primary key,
worktag character(32) not null default '' unique,
...
last_updated character(32) not null default '[Error]'
);
CREATE TABLE truefacts (
about character(32) not null primary key,
fact character(32) not null
);
The following:
CREATE TRIGGER zz_worktags_last_updated AFTER UPDATE ON worktags BEGIN
UPDATE worktags SET
last_updated = truefacts.fact WHERE truefacts.about = 'Last Worktag Update';
END;
gives the error:
Error: near line 52: no such column: truefacts.fact
But the column exists, and the syntax diagram seems to indicate that
[[schema-name . ] table-name . ] column-name
is a legal expr for the right-side of a SET column-name = expr.

You would need to use a subquery to access the other (truefacts) table (as there is no FROM truefacts anywhere) e.g. :-
CREATE TRIGGER zz_worktags_last_updated AFTER UPDATE ON worktags BEGIN
UPDATE worktags SET
last_updated = (SELECT fact FROM truefacts WHERE about = 'Last Worktag Update');
END;
Saying that, there is then no need for the TRIGGER as the subquery could be embedded into the UPDATE.
e.g. consider the following example :-
DROP TRIGGER IF EXISTS zz_worktags_last_updated;
DROP TABLE IF EXISTS worktags;
DROP TABLE IF EXISTS truefacts;
CREATE TABLE worktags (
worktag_id integer not null primary key,
worktag character(32) not null default '' unique,
last_updated character(32) not null default '[Error]'
);
CREATE TABLE truefacts (
about character(32) not null primary key,
fact character(32) not null
);
INSERT INTO truefacts VALUES('Last Worktag Update','xxx');
INSERT INTO worktags (worktag,last_updated) VALUES('mytag',(datetime('now')));
SELECT * FROM worktags;
UPDATE worktags SET last_updated = (SELECT fact FROM truefacts WHERE about = 'Last Worktag Update'), worktag = 'aaaa' WHERE worktag_id = 1;
SELECT * FROM worktags;
UPDATE truefacts SET fact = 'zzzz' WHERE rowid = 1;
CREATE TRIGGER zz_worktags_last_updated AFTER UPDATE ON worktags BEGIN
UPDATE worktags SET
last_updated = (SELECT truefacts.fact FROM truefacts WHERE truefacts.about = 'Last Worktag Update');
END;
UPDATE worktags SET worktag = 'bbbb' WHERE worktag_id = 1;
SELECT * FROM worktags;
This :-
Drops the tables and triggers if they exist (so it can be rerun)
Crate the 2 tables and populates them.
Selects everything from the worktags table (just the 1 row)
Updates the row in the worktags table using a subquery (this is the no trigger required example)
Selects everything from the updated (without a trigger) worktags table.
Updates the fact column of the truefacts (to show that the trigger works)
6.Creates the trigger.
Updates the row in the worktags table, changing the worktag column, leaving the change to the last_updated column to be done by the trigger.
Selects everything from the updated by the trigger worktags table.
Running the above results in :-
and lastly

Related

Cannot insert data in trigger

It give me error example image at below:
Trigger code:
CREATE OR REPLACE TRIGGER InsertNewStaffs
BEFORE INSERT ON Staffs
FOR EACH ROW
ENABLE
DECLARE
v_user varchar(255);
v_date varchar(255);
v_Staffs_ID Staffs.Staffs_ID%TYPE;
v_Staffs_Name Staffs.Staffs_Name%TYPE;
v_Staffs_Contact_Number Staffs.Staffs_Contact_Number%TYPE;
v_Staffs_Email Staffs.Staffs_Email%TYPE;
v_Orders_ID Staffs.Orders_ID%TYPE;
v_count INTEGER;
BEGIN
SELECT count(*) INTO v_count FROM Staffs
WHERE Staffs_ID = v_Staffs_ID OR
Staffs_Name = v_Staffs_Name OR
Staffs_Contact_Number = v_Staffs_Contact_Number OR
Staffs_Email = v_Staffs_Email;
IF v_count > 0 THEN
RAISE_APPLICATION_ERROR(-20000, 'Oops, some data is already exists. Please try again...');
DBMS_OUTPUT.PUT_LINE('Oops, some data is already exists. Please try again...');
SELECT user, TO_CHAR(sysdate, 'DD/MON/YYYY HH24:MI:SS') INTO v_user, v_date FROM dual;
ELSE
INSERT INTO Staffs(Staffs_ID, Staffs_Name, Staffs_Contact_Number, Staffs_Email, Orders_ID)
VALUES(v_Staffs_ID, v_Staffs_Name, v_Staffs_Contact_Number, v_Staffs_Email, v_Orders_ID);
DBMS_OUTPUT.PUT_LINE('One Row Inserted By ' || v_user || CHR(10));
DBMS_OUTPUT.PUT_LINE('Inserted data at ' || v_date);
INSERT INTO monitorInsertStaffs(user_name, entry_date, operation)
VALUES(v_user, v_date, 'Insert');
END IF;
END;
/
My Table:
CREATE TABLE Staffs(
Staffs_ID char(20) NOT NULL,
Staffs_Name varchar(255) NOT NULL,
Staffs_Contact_Number varchar(50) NOT NULL,
Staffs_Email varchar(255) NOT NULL,
Orders_ID char(20),
PRIMARY KEY (Staffs_ID),
FOREIGN KEY (Orders_ID) REFERENCES Orders(Orders_ID)
);
CREATE TABLE Orders(
Orders_ID char(20) NOT NULL,
Order_Date DATE NOT NULL,
Order_Status varchar(255) NOT NULL,
Order_Quantity int NOT NULL,
Order_TotalAmount NUMERIC(10,2) NOT NULL,
Order_TotalPrice NUMERIC(10,2) NOT NULL,
PRIMARY KEY (Orders_ID),
Pets_Products_ID char(20),
CustomerID char(20),
FOREIGN KEY (Pets_Products_ID) REFERENCES Pets_Products(Pets_Products_ID),
FOREIGN KEY (CustomerID) REFERENCES Customers(CustomerID)
);
I try to insert data and if the data has existed it will show RAISE_APPLICATION_ERROR(-20000, 'Oops, some data is already exists. Please try again...'); but it didn't show the message and also cannot insert data when no exists the data.
I don't know where is error code that I find.
The whole concept is just wrong.
you've based trigger on a table into which you're just inserting a row (staffs)
then you're selecting from the same table (it'll raise the mutating table error if you try to insert more than a single row)
the where clause uses local variables that have no values
insert into staffs cause the same trigger to fire over and over again, until Oracle concludes that that's enough and raises the error
Don't use a trigger. Use UNIQUE constraints:
CREATE TABLE Staffs(
Staffs_ID char(20) NOT NULL,
Staffs_Name varchar(255) NOT NULL,
Staffs_Contact_Number varchar(50) NOT NULL,
Staffs_Email varchar(255) NOT NULL,
Orders_ID char(20),
PRIMARY KEY (Staffs_ID),
UNIQUE (Staffs_Name),
UNIQUE (Staffs_Contact_Number),
UNIQUE (Staffs_Email),
FOREIGN KEY (Orders_ID) REFERENCES Orders(Orders_ID)
);
(However, you should also consider whether your business requirements make sense or if you can have multiple staff members called Jane Smith or if you can have two staff members who share an office with the same telephone number?)
If you want to use a logging table then use an autonomous transaction to just insert into that table:
CREATE OR REPLACE TRIGGER InsertNewStaffs
BEFORE INSERT ON Staffs
FOR EACH ROW
ENABLE
DECLARE
PRAGMA AUTONOMOUS_TRANSACTION;
BEGIN
INSERT INTO monitorInsertStaffs(
user_name, entry_date, operation
) VALUES(
:NEW.Staffs_ID, SYSDATE, 'Insert'
);
COMMIT;
END;
/
db<>fiddle here

Creating trigger to compare dates from two tables [duplicate]

This question already has an answer here:
Checking if date in table B is between date in Table A before inserting SQLite
(1 answer)
Closed 1 year ago.
I have two tables that both have separate start/end date values in them. One Project can contain many Plans, and a specific Plan start/end date should be between its Project start/end date. I dont know how to validate this, and I have tried to use triggers but I just cant figure it out. Can someone give me some pointers on what I'm doing wrong?
This is my trigger:
%%sql
CREATE TRIGGER beforeInsertInPlan BEFORE INSERT ON Plan FOR EACH ROW
BEGIN
SELECT proID.projectID FROM Project
INNER JOIN Project ON pID = Project.projectID
WHERE
And here are my two tables:
%%sql
DROP TABLE IF EXISTS Project;
CREATE TABLE Project (
projectID varchar(255) NOT NULL UNIQUE,
name varchar(255) NOT NULL DEFAULT ' ',
leader varchar(255) NOT NULL DEFAULT ' ',
budget varchar(255) NOT NULL DEFAULT '0',
startDate DATE NOT NULL DEFAULT '2000-12-31',
endDate DATE NOT NULL DEFAULT '2000-12-31'
CHECK (JulianDay(startDate) <= JulianDay(endDate)),
PRIMARY KEY (projectID)
);
and:
%%sql
DROP TABLE IF EXISTS Plan;
CREATE TABLE Plan (
pID varchar(255) NOT NULL UNIQUE,
projectID varchar(255) DEFAULT NULL,
name varchar(255) NOT NULL DEFAULT ' ',
startDate DATE NOT NULL DEFAULT ' ',
endDate DARE NOT NULL DEFAULT ' '
CHECK (JulianDay(startDate) <= JulianDay(endDate) AND (startDate >= Project.startDate) AND
(endDate <= Project.endDate)),
PRIMARY KEY (pID, projectID),
FOREIGN KEY (projectID) REFERENCES Project(projectID)
);
First a BEFORE INSERT trigger will probably result in nothing but issues. see https://sqlite.org/lang_createtrigger.html#cautions_on_the_use_of_before_triggers
So here's a trigger that I believe will work as intended albeit it deleting the inserted row:-
CREATE TRIGGER IF NOT EXISTS afterInsertInPlan
AFTER INSERT ON plan
WHEN (
(NOT (new.startdate) BETWEEN
(SELECT startdate FROM project WHERE projectID = new.projectID)
AND
(SELECT enddate FROM project WHERE projectID = new.projectID)
)
OR
(NOT (new.enddate) BETWEEN
(SELECT startdate FROM project WHERE projectID = new.projectID)
AND
(SELECT enddate FROM project WHERE projectID = new.projectID)
)
)
BEGIN
DELETE FROM plan WHERE pID = new.pID ;
END
;
Testing/Demo
The above was tested using :-
DROP TABLE IF EXISTS Project;
CREATE TABLE Project (
projectID varchar(255) NOT NULL UNIQUE,
name varchar(255) NOT NULL DEFAULT ' ',
leader varchar(255) NOT NULL DEFAULT ' ',
budget varchar(255) NOT NULL DEFAULT '0',
startDate DATE NOT NULL DEFAULT '2000-12-31',
endDate DATE NOT NULL DEFAULT '2000-12-31'
CHECK (JulianDay(startDate) <= JulianDay(endDate)),
PRIMARY KEY (projectID)
);
DROP TABLE IF EXISTS Plan;
CREATE TABLE Plan (
pID varchar(255) NOT NULL UNIQUE,
projectID varchar(255) DEFAULT NULL,
name varchar(255) NOT NULL DEFAULT ' ',
startDate DATE NOT NULL DEFAULT ' ' ,
endDate DATE NOT NULL DEFAULT ' ',
CHECK (endDate >= startDate),
PRIMARY KEY (pID, projectID),
FOREIGN KEY (projectID) REFERENCES Project(projectID)
);
DROP TABLE IF EXISTS trigger_log;
CREATE TABLE IF NOT EXISTS trigger_log (id INTEGER PRIMARY KEY, timestamp TEXT DEFAULT CURRENT_TIMESTAMP, trigger_text TEXT);
DROP TRIGGER IF EXISTS beforeInsertInPlan;
CREATE TRIGGER IF NOT EXISTS afterInsertInPlan
AFTER INSERT ON plan
WHEN (
(NOT (new.startdate) BETWEEN
(SELECT startdate FROM project WHERE projectID = new.projectID)
AND
(SELECT enddate FROM project WHERE projectID = new.projectID)
)
OR
(NOT (new.enddate) BETWEEN
(SELECT startdate FROM project WHERE projectID = new.projectID)
AND
(SELECT enddate FROM project WHERE projectID = new.projectID)
)
)
BEGIN
DELETE FROM plan WHERE pID = new.pID ;
INSERT INTO trigger_log (trigger_text) VALUES('DELETED FROM Plan Table due to date(s) not within project. pID was '||new.pID);
END
;
INSERT INTO project VALUES ('P1','P1','Mary',100,'2021-09-01','2022-09-30');
INSERT INTO plan VALUES ('P1P1','P1','Plan1','2021-09-01','2022-09-30');
INSERT INTO plan VALUES ('P1P2','P1','Plan2','2021-08-01','2022-09-30'); /* X */
INSERT INTO plan VALUES ('P1P3','P1','Plan3','2021-09-01','2022-10-30'); /* X */
INSERT INTO plan VALUES ('P1P4','P1','Plan4','2020-09-01','2022-10-30'); /* X */
INSERT INTO plan VALUES ('P1P5','P1','Plan5','2021-09-01','2021-10-01');
INSERT INTO plan VALUES ('P1P6','P1','Plan6','2021-10-01','2021-11-01');
INSERT INTO plan VALUES ('P1P7','P1','Plan7','2021-11-01','2021-12-01');
SELECT * FROM plan;
/* Cleanup Environment */
SELECT * FROM trigger_log;
DROP TABLE IF EXISTS trigger_log;
DROP TRIGGER IF EXISTS beforeInsertInPlan;
DROP TABLE IF EXISTS Plan;
DROP TABLE IF EXISTS Project;
When run then the results are :-
The Plan's in the plan table:-
i.e. those commented with an X (3) were not inserted
The trigger_log (used to confirm triggering when testing) :-
i.e. the 3 commented with an X that were not inserted have been logged accordingly.
Example of why not to use a BEFORE INSERT trigger
Swapping the trigger to use BEFORE INSERT and :-
All are inserted :-
None are deleted even though logged:-
i.e. nothing to delete as nothing has been inserted.

how to insert row on table B when table A is updated, using a trigger in SQLlite

Table A
userID
Name
Table B
UserID
Timestamp
I need to create a trigger to insert a row in table B, when A.Name changes. so far, i have:
CREATE TRIGGER NameUpdate
AFTER UPDATE OF Name
ON A
FOR EACH ROW
BEGIN
INSERT INTO B(
UserID,
Timestamp
)
VALUES (
xxxxxxx,
DateTime('now')
);
END;
XXXXXXX should be A.UserID that just changed.
You can refer to the before/after values (according to relevance i.e. only new for inserts, old or new for updates and only old for deletes) using a prefix of old. or new. respectively.
Try :-
CREATE TRIGGER NameUpdate AFTER UPDATE OF Name ON A FOR EACH ROW
BEGIN
INSERT INTO B( UserID, Timestamp ) VALUES ( new.UserID, DateTime('now') );
END
;
Or (as the UserID column hasn't changed) :-
CREATE TRIGGER NameUpdate AFTER UPDATE OF Name ON A FOR EACH ROW
BEGIN
INSERT INTO B( UserID, Timestamp ) VALUES ( old.UserID, DateTime('now') );
END
;

Oracle trigger to prevent specified value wrote into column

I'm working on Oracle 11g 64bit.
Say I have a table named "MyTable", I'm trying to monitoring a column named "My_Name".
When "My_Name" is going to be changed to '' (before update), I want to stop it and change "My_Name" back to old value. In other word, '' isn't a legal value for the "My_Name" column.
Here's what I did so far, no compilation error, but no effect, I can still write the '' value into "My_Name" column.
CREATE OR REPLACE TRIGGER MyTable_tracking
BEFORE INSERT OR UPDATE ON MyDB.MyTable REFERENCING NEW AS newValue OLD AS oldValue
FOR EACH ROW
DECLARE
v_old VARCHAR(20);
v_new VARCHAR(20);
BEGIN
IF INSERTING THEN
v_new:=:newValue.My_Name; --Trigger checks column 'My_Name' only
ELSIF UPDATING THEN
v_old:=:oldValue.My_Name; --Trigger checks column 'My_Name' only
v_new:=:newValue.My_Name; --Trigger checks column 'My_Name' only
--IF :newValue.My_Name='' THEN
IF LENGTH(TRIM(:newValue.My_Name))=0 THEN
:newValue.My_Name:=:oldValue.My_Name;
END IF;
END IF;
END;
How can I do this?
No need for a trigger. In Oracle an empty string '' and null are the same thing. So just define my_name as NOT NULL and you can't put null or '' in it.
SQL> create table my_table (id integer primary key, my_name varchar(20) not null);
Table created.
SQL> insert into my_table values (1, 'Arthur');
1 row created.
SQL> update my_table set my_name = '' where id = 1;
update my_table set my_name = '' where id = 1
*
ERROR at line 1:
ORA-01407: cannot update ("ARTHUR"."MY_TABLE"."MY_NAME") to NULL
SQL> insert into my_table values (2, '');
insert into my_table values (2, '')
*
ERROR at line 1:
ORA-01400: cannot insert NULL into ("ARTHUR"."MY_TABLE"."MY_NAME")
SQL>
If you can't use the most efficient solution because of external restrictions (which I find highly questionable), you can use something like this:
create or replace trigger slow_not_null_check
before insert or update on my_table
for each row
begin
if inserting and :new.my_name is null then
:new.my_name := 'No NULL allowed';
end if;
if updating and :new.my_name is null then
:new.my_name := :old.my_name;
end if;
end;
/
This will silently convert, '' to 'No NULL allowed' when inserting and will restore the previous value when updating:
insert into my_table values (1, '');
insert into my_table values (2, 'Arthur');
select * from my_table;
ID | MY_NAME
---+----------------
1 | No NULL allowed
2 | Arthur
update my_table
set my_name = ''
where id = 2;
select *
from my_table;
ID | MY_NAME
---+----------------
1 | No NULL allowed
2 | Arthur
I fixed my problem whit following code
IF INSERTING THEN
v_new:=:newValue.My_Name;
ELSIF UPDATING THEN
v_old:=:oldValue.My_Name;
v_new:=:newValue.My_Name;
--IF :newValue.My_Name='some specified value' THEN --not allow some value
--IF :newValue.My_Name='' --not working
IF :newValue.My_Name='' OR :newValue.My_Name IS NULL THEN --not allow '' or null
:newValue.My_Name:=v_old; --works
--:newValue.My_Name:=:oldValue.My_Name; --not working, use variable instead
END IF;
END IF;

Drop primary key and add in Transact-SQL

I've researched and tried everything, I don't know if I'm missing something but here is my attempt at a dropping the primary key
Alter Table Course
Drop constraint PK_Course_CourseID
Go
Table name is Course and the PK is CourseID. I then need to re-add the PK constraint to column "row"
To delete a primary key constraint:
In Object Explorer, right-click the table with the primary key, and click Design.
The table opens in Table Designer.
In the table grid, right-click the row with the primary key and choose Remove Primary Key to toggle the setting from on to off.
Source:
https://msdn.microsoft.com/en-us/library/ms190621(v=sql.105).aspx
Drop primary key:
DECLARE #table NVARCHAR(512), #sql NVARCHAR(MAX);
SELECT #table = N'dbo.Course';
SELECT #sql = 'ALTER TABLE ' + #table
+ ' DROP CONSTRAINT ' + name + ';'
FROM sys.key_constraints
WHERE [type] = 'PK'
AND [parent_object_id] = OBJECT_ID(#table);
EXEC sp_executeSQL #sql;
Change previous column type (if was seed/auto-increment):
ALTER TABLE dbo.Course
ALTER COLUMN YourColumnName INT
Add PK
ALTER TABLE Course ADD PRIMARY KEY (id)
Hope this helps!
DECLARE #V_CONSTRAINTNAME NVARCHAR(256);DECLARE #V_QUERY NVARCHAR(1000);BEGINSELECT #V_CONSTRAINTNAME = constraint_name FROM INFORMATION_SCHEMA.table_constraints WHERE table_name = 'Course'AND constraint_type ='PRIMARY KEY';IF #V_CONSTRAINTNAME IS NOT NULL BEGINSET #V_QUERY = 'ALTER TABLE #DBNAME#.#USERNAME#.Course DROP CONSTRAINT '+ #V_CONSTRAINTNAME;exec sp_executesql #V_QUERY;END;ENDGO
DECLARE #V_COUNT INT;BEGINSET #V_COUNT = 0;SELECT #V_COUNT = COUNT(*) FROM INFORMATION_SCHEMA.table_constraints WHERE TABLE_NAME = 'Course' AND CONSTRAINT_TYPE = 'PRIMARY KEY';IF #V_COUNT = 0BEGINEXEC SP_EXECUTESQL N'ALTER TABLE #DBNAME#.#USERNAME#.Course ADD CONSTRAINT PK_Course_CourseID PRIMARY KEY (row)';END;END;GO

Resources