Trigger with current date query/where clause - sql

we want to create a trigger which checks if a new measurement (=messung) point lies within the current glacier shape (=umriss).
are tables look like this:
glacier shape (=Umriss)
create table umriss
(
umr_nr number (4) not null,
umr_datum date,
GLST_ID number (4) not null,
shape mdsys.sdo_geometry,
GLETSCHER_ID number (3) not null
)
;
alter table umriss
add constraint umriss_glst_pk
primary key (umr_nr, GLST_ID, GLETSCHER_ID)
;
ALTER TABLE umriss
ADD CONSTRAINT umriss_gletscherstand_fk
FOREIGN KEY (GLST_ID, GLETSCHER_ID)
REFERENCES GLETSCHERSTAND(GLST_ID, GLETSCHER_ID);
new measurement (=Messung)
CREATE TABLE MESSUNG
(
MESS_NR number (4) not null,
MESS_DAT date,
MESS_AKK number (20) NOT NULL,
MESS_SCHMELZ number (20) NOT NULL,
SHAPE mdsys.sdo_geometry,
MESS_BILD blob,
KMPGN_NR NUMBER (4) NOT NULL
);
ALTER TABLE MESSUNG
ADD CONSTRAINT messung_pk
PRIMARY KEY (MESS_NR);
ALTER TABLE MESSUNG
ADD CONSTRAINT messung_messkampagne_fk
FOREIGN KEY (KMPGN_NR)
REFERENCES MESSKAMPAGNE(KMPGN_NR);
Trigger
CREATE OR REPLACE
TRIGGER MESSUNG_in_UMRISS_TRI
BEFORE INSERT OR UPDATE ON MESSUNG
FOR EACH ROW
DECLARE
num_check NUMBER;
BEGIN
SELECT COUNT (*) INTO num_check
FROM UMRISS u
WHERE mdsys.sdo_contains (u.shape, :NEW.point) = 'TRUE';
IF num_check <> 1
THEN
RAISE_APPLICATION_ERROR (=20500, 'Messung in keinem Umriss')
END IF;
END;
How do we iplement the function so the trigger only checks within the most curretn glacier shape?
Thanks for your help!

This will return the one row fron UMRISS which matches the most recent date in the table.
SELECT COUNT (*) INTO num_check
FROM UMRISS u
WHERE mdsys.sdo_contains (u.shape, :NEW.point) = 'TRUE'
AND u.umr_datum = ( select max(d.;umr_datum) from UMRISS d );
This sort of query is the price for keeping historical data in teh same table as the current record.

it seems that POINT ist not defined in your example?
However, you might consider a check constraint because a trigger would only be enforced when a MESSUNG record is inserted or updated, but not when UMRISS is changed
alter table MESSUNG add constraint MESSUNG_CC_CONTAINS check(mdsys.sdo_contains (shape, point) = 'TRUE')
In case you're frequently updating the UMRISS records it might not be feasable at all to enforce such a constraint because Oracle would have to check all MESSUNG records when UMRISS is updated or deleted. Perhaps consider an additional mapping table between MESSUNG and UMRISS that you can update separately.

Related

SQL - How do you use a user defined function to constrain a value between 2 tables

First here's the relevant code:
create table customer(
customer_mail_address varchar(255) not null,
subscription_start date not null,
subscription_end date, check (subscription_end !< subcription start)
constraint pk_customer primary key (customer_mail_address)
)
create table watchhistory(
customer_mail_address varchar(255) not null,
watch_date date not null,
constraint pk_watchhistory primary key (movie_id, customer_mail_address, watch_date)
)
alter table watchhistory
add constraint fk_watchhistory_ref_customer foreign key (customer_mail_address)
references customer (customer_mail_address)
on update cascade
on delete no action
go
So i want to use a UDF to constrain the watch_date in watchhistory between the subscription_start and subscription_end in customer. I can't seem to figure it out.
Check constraints can't validate data against other tables, the docs say (emphasis mine):
[ CONSTRAINT constraint_name ]
{
...
CHECK [ NOT FOR REPLICATION ] ( logical_expression )
}
logical_expression
Is a logical expression used in a CHECK constraint and returns TRUE or
FALSE. logical_expression used with CHECK constraints cannot
reference another table but can reference other columns in the same
table for the same row. The expression cannot reference an alias data
type.
That being said, you can create a scalar function that validates your date, and use the scalar function on the check condition instead:
CREATE FUNCTION dbo.ufnValidateWatchDate (
#WatchDate DATE,
#CustomerMailAddress VARCHAR(255))
RETURNS BIT
AS
BEGIN
IF EXISTS (
SELECT
'supplied watch date is between subscription start and end'
FROM
customer AS C
WHERE
C.customer_mail_address = #CustomerMailAddress AND
#WatchDate BETWEEN C.subscription_start AND C.subscription_end)
BEGIN
RETURN 1
END
RETURN 0
END
Now add your check constraint so it validates that the result of the function is 1:
ALTER TABLE watchhistory
ADD CONSTRAINT CHK_watchhistory_ValidWatchDate
CHECK (dbo.ufnValidateWatchDate(watch_date, customer_mail_address) = 1)
This is not a direct link to the other table, but a workaround you can do to validate the date. Keep in mind that if you update the customer dates after the watchdate insert, dates will be inconsistent. The only way to ensure full consistency in this case would be with a few triggers.

how to check Composite Primary key before inserting new values

I have a table with multiple columns which consists of a composite primary key for three of them (columns customer_id,system_origin,policy_number).
The table is created as below :
Create table LOST_MEMBER_ACCESS_LOG (
Customer_id varchar2(20) NOT NULL,
System_Origin varchar2(20) NOT NULL,
Policy_Number varchar2(20) NOT_NULL,
PRIMARY_KEY(Customer_id,System_Origin, Policy_Number)
);
I have a requirement to write a stored proc which firsts checks if a row already exists for unique combination for customer_id,system_origin,policy_number then it updates the already existing row with the new values or else it inserts a new row.
What you're saying you want to do is:
if row exists then
update ...
else
insert ...
end if;
But there is easier way. Just do the update and check if any row was touched
update lost_member_access_log
set ...
where ... ;
if sql%rowcount = 0 then
insert into lost_member_access_log ...
end if;
MERGE is of course also an option.

Adding a NOT NULL column to a Redshift table

I'd like to add a NOT NULL column to a Redshift table that has records, an IDENTITY field, and that other tables have foreign keys to.
In PostgreSQL, you can add the column as NULL, fill it in, then ALTER it to be NOT NULL.
In Redshift, the best I've found so far is:
ALTER TABLE my_table ADD COLUMN new_column INTEGER;
-- Fill that column
CREATE TABLE my_table2 (
id INTEGER IDENTITY NOT NULL SORTKEY,
(... all the fields ... )
new_column INTEGER NOT NULL,
PRIMARY KEY(id)
) DISTSTYLE all;
UNLOAD ('select * from my_table')
to 's3://blah' credentials '<aws-auth-args>' ;
COPY my_table2
from 's3://blah' credentials '<aws-auth-args>'
EXPLICIT_IDS;
DROP table my_table;
ALTER TABLE my_table2 RENAME TO my_table;
-- For each table that had a foreign key to my_table:
ALTER TABLE another_table ADD FOREIGN KEY(my_table_id) REFERENCES my_table(id)
Is this the best way of achieving this?
You can achieve this w/o having to load to S3.
modify the existing table to create the desired column w/ a default value
update that column in some way (in my case it was copying from another column)
create a new table with the column w/o a default value
insert into the new table (you must list out the columns rather than using (*) since the order may be the same (say if you want the new column in position 2)
drop the old table
rename the table
alter table to give correct owner (if appropriate)
ex:
-- first add the column w/ a default value
alter table my_table_xyz
add visit_id bigint NOT NULL default 0; -- not null but default value
-- now populate the new column with whatever is appropriate (the key in my case)
update my_table_xyz
set visit_id = key;
-- now create the new table with the proper constraints
create table my_table_xzy_new
(
key bigint not null,
visit_id bigint NOT NULL, -- here it is not null and no default value
adt_id bigint not null
);
-- select all from old into new
insert into my_table_xyz_new
select key, visit_id, adt_id
from my_table_xyz;
-- remove the orig table
DROP table my_table_xzy_events;
-- rename the newly created table to the desired table
alter table my_table_xyz_new rename to my_table_xyz;
-- adjust any views, foreign keys or permissions as required

Confused with Oracle Procedure with sequence, linking errors and filling null fields

I am trying to make a procedure that takes makes potential empty "received" fields use the current date. I made a sequence called Order_number_seq that populates the order number (Ono) column. I don't know how to link errors in the orders table to a entry in the Orders_errors table.
this is what i have so far:
CREATE PROCEDURE Add_Order
AS BEGIN
UPDATE Orders
CREATE Sequence Order_number_seq
Start with 1,
Increment by 1;
UPDATE Orders SET received = GETDATE WHERE received = null;
These are the tables I am working with:
Orders table
(
Ono Number Not Null,
Cno Number Not Null,
Eno Number Not Null,
Received Date Null,
Shipped_Date Date Null,
Creation_Date Date Not Null,
Created_By VARCHAR2(10) Not Null,
Last_Update_Date Date Not Null,
Last_Updated_By VARCHAR2(10) Not Null,
CONSTRAINT Ono_PK PRIMARY KEY (Ono),
CONSTRAINT Cno_FK FOREIGN KEY (Cno)
REFERENCES Customers_Proj2 (Cno)
);
and
Order_Errors table
(
Ono Number Not Null,
Transaction_Date Date Not Null,
Message VARCHAR(100) Not Null
);
Any help is appreciated, especially on linking the orders table errors to create a new entry in OrderErrors table.
Thanks in advance.
Contrary to Martin Drautzburg's answer, there is no foreign key for the order number on the Order_Errors table. There is an Ono column which appears to serve that purpose, but it is not a foreign as far as Oracle is concerned. To make it a foreign key, you need to add a constraint much like the Cno_FK on Orders. An example:
CREATE TABLE Order_Errors
(
Ono Number Not Null,
Transaction_Date Date Not Null,
Message VARCHAR(100) Not Null,
CONSTRAINT Order_Errors_Orders_FK FOREIGN KEY (Ono) REFERENCES Orders (Ono)
);
Or, if your Order_Errors table already exists and you don't want to drop it, you can use an ALTER TABLE statement:
ALTER TABLE Order_Errors
ADD CONSTRAINT Order_Errors_Orders_FK FOREIGN KEY (Ono) REFERENCES Orders (Ono)
;
As for the procedure, I'm inclined to say what you're trying to do does not lend itself well to a PROCEDURE. If your intention is that you want the row to use default values when inserted, a trigger is better suited for this purpose. (There is some performance hit to using a trigger, so that's a consideration.)
-- Create sequence to be used
CREATE SEQUENCE Order_Number_Sequence
START WITH 1
INCREMENT BY 1
/
-- Create trigger for insert
CREATE TRIGGER Orders_Insert_Trigger
BEFORE INSERT ON Orders
FOR EACH ROW
DECLARE
BEGIN
IF :NEW.Ono IS NULL
THEN
SELECT Order_Number_Sequence.NEXTVAL INTO :NEW.Ono FROM DUAL;
END IF;
IF :NEW.Received IS NULL
THEN
SELECT CURRENT_DATE INTO :NEW.O_Received FROM DUAL;
END IF;
END;
/
This trigger will then be executed on every single row inserted into the Orders table. It checks if the Ono column was NULL and replaces it with an ID from the sequence if so. (Be careful that you don't ever provide an ID that will later be generated by the sequence; it will get a primary key conflict error.) It then checks if the received date is NULL and sets it to the current date, using the CURRENT_DATE function (which I believe was one of the things you were trying to figure out), if so.
(Side note: Other databases may not require a trigger to do this and instead could use a default value. I believe PostgreSQL, for instance, allows the use of function calls in its DEFAULT clauses, and that is how its SERIAL auto-increment type is implemented.)
If you are merely trying to update existing data, I would think the UPDATE statements by themselves would suffice. Is there a reason this needs to be a PROCEDURE?
One other note. Order_Errors has no primary key. You probably want to have an auto-incrementating surrogate key column, or at least create an index on its Ono column if you only ever intend to select off that column.
There are a number of confusing things in your question:
(1) You are creating a sequence inside a procedure. Does this even compile?
(2) Your procedure does not have any parameters. It just updates the RECEIVED column of all rows.
(3) You are not telling us what you want in the MESSAGE column.
My impression is that you should first go "back to the books" before you ask questions here.
As for your original question
how to link errors in the orders table to a entry in the Orders_errors
table.
This is aleady (correctly) done. The Orders_error table contains an ONO foreign key which points to an order.

oracle sql: insert spatial data from more existing table

I have created a table umriss which I filled with data and I still need to insert the geometry data from existing tables (usrdemo.glets_1850, usrdemo.glets_1973, ...). How does that work?
umriss is a "weak entity" and has references to the tables gletscherstand (glst_id) and gletscher (gletscher_id)
create table umriss
(
umr_nr number (4) not null,
umr_datum date,
GLST_ID number (4) not null,
shape mdsys.sdo_geometry,
GLETSCHER_ID number (3) not null,
se_anno_cad_data blob
);
alter table umriss
add constraint umriss_glst_pk
primary key (umr_nr, GLST_ID, GLETSCHER_ID);
ALTER TABLE umriss
ADD CONSTRAINT umriss_gletscherstand_fk
FOREIGN KEY (GLST_ID, GLETSCHER_ID)
REFERENCES GLETSCHERSTAND(GLST_ID, GLETSCHER_ID);
I manually inserted the data for the attributes umr_nr, umr_datum, glst_id and gletscher_id. As you can see from umr_nr there are 3 shapes and I now want to add the spatial data from usrdemo_glets_1850 which has 3 shapes and the attributes: objectid (= umr_nr in table umriss), shape and se_anno_cad_data.
I tried this...
INSERT INTO umriss u
(u.shape, u.se_anno_cad_data)
SELECT usrdemo.glets_1850.shape, usrdemo.glets_1850.se_anno_cad_data
FROM usrdemo.glets_1850;
...and got the message: Ora-01400 - cannot insert NULL into ..."umriss"."umr_nr"
How does this work?
You haved tried to insert new records into table umriss without setting values for the primary key column umr_nr.
If I have understood correctly, you have already manually inserted records into table umriss, and now what you need to do is to add addtional columns only, then you should use UPDATE instead.