Oracle Database Can set Constraint for Upper Case Values? - oracle

Is there anyway that we can set a constraint in database table level to have upper or lower case values for certain columns? When we create a table, we can set NOT NULL to avoid having null values on a column. Same way, can we do that for either uppercase or lower case?

You can do that using a check constraint:
create table foo
(
only_lower varchar(20) not null check (lower(only_lower) = only_lower),
only_upper varchar(20) not null check (upper(only_upper) = only_upper)
);

I had almost same case, tried with check constraint, but if the user is not mentioning it as UPPER() or LOWER() it gives error so I took TRIGGER route as below code.
--creating table
create table user_name (
first_name varchar2(50),
last_name varchar2(50));
--creating trigger
CREATE OR REPLACE TRIGGER TRG_USER_NAME_IU
BEFORE INSERT OR UPDATE ON USER_NAME
FOR EACH ROW
BEGIN
:NEW.FIRST_NAME := UPPER(:NEW.FIRST_NAME);
:NEW.LAST_NAME := UPPER(:NEW.LAST_NAME);
END;
/
Can test and share feedback or comments

Related

table NISHAN.TBL_ADMIN is mutating, trigger/function may not see it

I have a trigger named tr_admin_user_role that automatically insert values into tbl_user_role table when we perform a insert in another table called tbl_admin. There is no error at compile time but whenever I insert a value into tbl_admin table it shows me an error and error is like
This is my tbl_admin table
CREATE TABLE tbl_admin(
admin_id INTEGER,
username VARCHAR2(50) NOT NULL UNIQUE,
passwords VARCHAR2(50) NOT NULL,
email VARCHAR2(100) UNIQUE,
enabled CHAR(1) DEFAULT 1 NOT NULL,
created_at DATE DEFAULT SYSDATE NOT NULL,
CONSTRAINT pk_admin_id PRIMARY KEY(admin_id)
);
tbl_user_role table
CREATE TABLE tbl_user_role(
user_role_id INTEGER,
username VARCHAR2(50) NOT NULL,
user_role VARCHAR2(50) DEFAULT 'ROLE_ADMIN' NOT NULL,
CONSTRAINT pk_user_role_id PRIMARY KEY(user_role_id)
);
Trigger that i have created
CREATE OR REPLACE TRIGGER tr_admin_user_role
AFTER INSERT ON tbl_admin
FOR EACH ROW
DECLARE
new_username TBL_ADMIN.username%TYPE;
BEGIN
SELECT username INTO new_username FROM (
SELECT username FROM tbl_admin ORDER BY username DESC
) WHERE ROWNUM = 1;
INSERT INTO tbl_user_role(username, user_role) VALUES(new_username, 'ROLE_ADMIN');
END;
Insert statement
INSERT INTO tbl_admin(username, passwords) VALUES('nisha', 'nisha');
That's not how you fetch the newly inserted / updated / previous value of a column in a Trigger. You should use the :OLD.column_name and :NEW.column_name to refer the old and new column values.Read the documentation to understand more.
So, your Trigger could be rewritten as
CREATE OR REPLACE TRIGGER tr_admin_user_role AFTER
INSERT ON tbl_admin
FOR EACH ROW
BEGIN
INSERT INTO tbl_user_role (
username,
user_role
) VALUES (
:NEW.username,
'ROLE_ADMIN'
);
END;
/
I assume you are using another trigger to generate
admin_id and user_role_id since they are declared as PRIMARY KEYs
and you are not including them in your inserts.
Db fiddle demo
Here I've used dummy values for those columns.

Oracle trigger insert to other table then modify the original table

I have theses two tables:
TABLE ASSET_ENTRY_NOTE (
ID NUMBER NOT NULL, --PK
ASSETMDL_ID NUMBER NOT NULL, --FK
DEPT_ID NUMBER NOT NULL, --FK
LOCATION NVARCHAR2(100) NOT NULL,
ASSET_ID NUMBER, --FK TO ASSETS
ACCOUNT_ID NUMBER NOT NULL, --FK
TOTAL_DPRC_DURATION FLOAT(126) NOT NULL,
TOTAL_PROD_HRS FLOAT(126),
AMORTIZATION_PRCNTG FLOAT(126),
ACQUIRE_DATE DATE NOT NULL,
DESCRIPTION NVARCHAR2(200) NOT NULL,
APPRFLAG NUMBER DEFAULT 0 NOT NULL,
WRK_HRS FLOAT(126),
)
TABLE ASSETS (
ID NUMBER NOT NULL, --PK
ASSETMDL_ID NUMBER NOT NULL, --FK
DEPT_ID NUMBER NOT NULL,
LOCATION NVARCHAR2(100) NOT NULL, --FK
ACCOUNT_ID NUMBER NOT NULL,
ACQUIRE_DATE DATE NOT NULL,
TOTAL_DPRC_DURATION FLOAT(126),
BALANCE_CLOSING_DATE DATE,
SELL_VAL FLOAT(126),
RPLCMNT_DISCOUNT FLOAT(126),
DESCRIPTION NVARCHAR2(200) NOT NULL,
)
Note that there's a one to one relationship between the two tables (i.e. ASSET_ENTRY_NOTE.ASSET_ID is Unique.
When the ASSETS_ENTRY_NOTE.APPRFLAG is updated to 1 I have this trigger that:
gets a new primary key sequence for the ASSETS table.
insert data from ASSETS_ENTRY_NOTE to ASSETS.
updates the column ASSETS_ENTRY_NOTE.ASSET_ID to the same value as the primary key value on the sequence.
This is the latest try for my trigger:
CREATE OR REPLACE TRIGGER ENTRYNT_ASSET_TRIG
after UPDATE OF APPRFLAG ON ASSET_ENTRY_NOTE
for each row
when (new.apprflag = 1)
declare
v_asset_id number;
BEGIN
SELECT assets_PK_SEQ.NEXTVAL INTO v_asset_id
FROM DUAL d;
insert into assets (ID,
assets.assetmdl_id,
assets.dept_id,
assets.location,
assets.account_id,
assets.acquire_date,
assets.total_dprc_duration,
assets.description
)
values (v_asset_id,
assetmdl_id,
dept_id,
location,
account_id,
acquire_date,
total_dprc_duration,
description
);
update ASSET_ENTRY_NOTE set asset_id = v_asset_id where ;
END;
The thing is, I know that ASSET_ENTRY_NOTE is a mutating table and the last UPDATE statement is not allowed here, But nothing else is working for me.
What I've already tried:
creating a statement-level trigger to update one value only.
using before instead of after but that's incorrect because I need the values just to insert into the ASSETS.
using a cursor to go through each value changed but I had exact fetch error.
creating a procedure that handles inserting and updating.
Any help would be appreciated.
The design seems quite strange to me, but to answer the question about the trigger:
To change the asset_entry_note row in the trigger, you need a before update trigger. In there you can just assign the value to the asset_id column.
Your insert statement is also wrong. You can table-qualify column names in the column list of an insert statement. And the values clause needs to use the values from the inserted row. You are referencing the target table's columns which is not allowed).
You also don't need a select statement to obtain the sequence value.
Putting all that together, your trigger should look something like this:
CREATE OR REPLACE TRIGGER ENTRYNT_ASSET_TRIG
BEFORE UPDATE OF APPRFLAG ON ASSET_ENTRY_NOTE
for each row
when (new.apprflag = 1)
declare
v_asset_id number;
BEGIN
v_asset_id := assets_PK_SEQ.NEXTVAL;
insert into assets
(ID,
assetmdl_id,
dept_id,
location,
account_id,
acquire_date,
total_dprc_duration,
description)
values
(v_asset_id,
new.assetmdl_id, -- reference the inserted row here!
new.dept_id,
new.location,
new.account_id,
new.acquire_date,
new.total_dprc_duration,
new.description);
new.asset_id := v_asset_id;
END;
/
You have to change the design of the application to have only one table with sign to indicate the membership of a particular entity.
Another way is to create 'after statement' trigger to update all affected rows in ASSET_ENTRY_NOTE with proper values. These rows is to be collected in, for example, package collection in row-level trigger.
I fixed it and it worked:
changed to before.
edited the update statement to an assignment of new so that the last line would become :new.asset_id := v_asset_id ;

Creating Triggers to check conflicts

My task is to check there are no conflicts with day and time when you insert or update a group fitness class on a customer timetable. Can someone please help me out. These are the tables I've got:
Name Null Type
------------- -------- ------------
CUSTOMER_T_ID NOT NULL NUMBER(38)
C_DATE NOT NULL TIMESTAMP(6)
TIMETABLE_ID NOT NULL NUMBER(38)
CUSTOMER_ID NOT NULL NUMBER(38)
Desc Timetable
Name Null Type
----------------- -------- ------------
TIMETABLE_ID NOT NULL NUMBER(38)
CLASS_DAY NOT NULL VARCHAR2(50)
CLASS_LOCATION NOT NULL VARCHAR2(50)
CLASS_START_TIME NOT NULL TIMESTAMP(6)
CLASS_FINISH_TIME NOT NULL TIMESTAMP(6)
WORKOUT_CLASS_ID NOT NULL NUMBER(38)
TRAINER_ID NOT NULL NUMBER(38)
Desc Workout_class
Name Null Type
---------------- -------- -------------
WORKOUT_CLASS_ID NOT NULL NUMBER(38)
NAME NOT NULL VARCHAR2(20)
WORKOUT_TYPE NOT NULL VARCHAR2(200)
EQUIPMENT_USED NOT NULL VARCHAR2(200)
RESULTS NOT NULL VARCHAR2(200)
COST NOT NULL FLOAT(126)
INTENSITY_LEVEL NOT NULL VARCHAR2(50)
CLASS_DURATION NOT NULL NUMBER(38)
Desc Customers
Name Null Type
---------------- -------- -------------
CUSTOMER_ID NOT NULL NUMBER(38)
FIRST_NAME NOT NULL VARCHAR2(50)
LAST_NAME NOT NULL VARCHAR2(50)
AGE NOT NULL NUMBER(38)
ADDRESS NOT NULL VARCHAR2(100)
CITY NOT NULL VARCHAR2(50)
MOBILE_PHONE NOT NULL NUMBER(10)
EMAIL VARCHAR2(50)
PICTURE BFILE()
CUSTOMER_TYPE_ID NOT NULL NUMBER(5)
Trigger is compiling but when i try to insert the same customer to the same timetable he is already into its not raising an error but the row is inserted
create or replace trigger timetableconflict
before insert or update on customer_timetable
for each row
begin
if :new.customer_T_ID = :old.Customer_T_ID and :new.Customer_ID = :old.Customer_ID
then
raise_application_error(-20000,'customer cannot enrol into same class again');
end if;
end;
Your trigger is comparing the OLD and NEW pseudorecords. When you insert a new row there is no OLD row in the table so all the fields in that record are null; your comparison therefore doesn't match. (You can't compare anything with null but that's a separate discussion). The condition you've used can never be matched on insert. When you update you're comparing the existing value for the field in the row being updated, with the new value you're updating it too; so you're currently saying that an update must change the customer_t_id and customer_id. Aside from anything else it looks like customer_t_id is probably supposed to be a primary key, so changing that would normally not be a good idea.
So I think you're misunderstanding what OLD represents. It looks like the customer_t_id reference is a mistake and you're trying to make sure there is not already a record for the customer in the table - but OLD does not tell you that as it only refers to the current row affected by the statement, not any other rows in the table.
I don't think that's actually your end goal from what you said in the question - I think you don't want a customer to have the same timetable twice.
Given that OLD doesn't do what you want, you might think about querying the table to see if such a row already exists. But you can't (easily) do that in a trigger; if you're inserting or updating more than one row at a time then you'll get a mutating table error. It's easy to abuse triggers by trying to make them do something they weren't designed for.
The normal way to enforce that uniqueness is with a unique constraint (or "unique composite key") rather than a trigger:
alter table customer_timetable
add constraint timetableconflict unique (customer_id, timetable_id);
That will also create a unique index to back it up; you could just create a unique index directly but declaring a constraint is more explicit. (It's not a great constraint name but I've just copied what you were going to call the trigger).
You can read more about how triggers and constraints differ:
Constraints are easier to write and less error-prone than triggers that enforce the same rules. However, triggers can enforce some complex business rules that constraints cannot. Oracle strongly recommends that you use triggers to constrain data input only in these situations:
To enforce referential integrity when child and parent tables are on different nodes of a distributed database
To enforce complex business or referential integrity rules that you cannot define with constraints
What you're describing doesn't fall into those categories.

Trigger to enter deleted entries to a new table - SQL plus

I am trying to create a trigger which will enter values into a table terminated_employees when we delete values from the nm_employees table. I have written the trigger but it does not work. Is my trigger format right? Any ideas?
CREATE TABLE nm_departments(
dept2 varchar(20),
CONSTRAINT empPK PRIMARY KEY (dept2)
);
CREATE TABLE nm_employees(
name varchar(20),
dept varchar(20),
CONSTRAINT departments FOREIGN KEY (dept) REFERENCES nm_departments (dept2)ON DELETE CASCADE
);
CREATE TABLE terminated_employees(
te_name varchar(20),
te_dept varchar(20)
);
CREATE TRIGGER term_employee AFTER DELETE ON nm_employee
FOR EACH ROW
BEGIN
INSERT INTO terminated_employees (NEW.te_name, NEW.te_dept) VALUES (OLD.name,OLD.dept)
END;
You should not be specifying the NEW. on the column names of your INSERT statement. These are the columns in the terminated_employees table, NOT the new values. i.e.
INSERT INTO terminated_employees (te_name, te_dept)
VALUES (OLD.name,OLD.dept)
You can use show errors (or show err) in SQL*Plus to see the exact error.
You have a number of problems:
Wrong table name on create trigger (missing the s)
Missing ; after instert statement
The OLD. need to have : prefix. i.e. :OLD.name

how to modify a constraint in sql plus?

I have created a table as follows:
create table emp( emp_id number(5) primary key
, emp_name varchar(20) not null
, dob date );
After the table has been created how would I change the constraint not null to unique or any other constraint in SQL*Plus?
You don't change a constraint from one type to another. You can add a unique constraint to the table
ALTER TABLE emp
ADD ( COSTRAINT uk_emp_name UNIQUE( emp_name ) );
That is independent of whether emp_name is allowed to have NULL values.
Just use ALTER TABLE command. For details look here: http://docs.oracle.com/cd/B28359_01/server.111/b28286/statements_3001.htm#i2103817
We cant be able to modify the already added constraint. Just we have to drop the constraint and add the new one with the same name, but add it with the necessary changes.
ALTER TABLE table_name drop constraint contraint_name;
alter table tablename add constraint containt_name CHECK (column_name IN (changes in the contraint)) ENABLE;

Resources