Writing CASE statement Error ORA-00923 - sql

I have a database that I have populated using CREATE and INSERT INTO statements. I am now trying to write a CASE statemenet that will display 'customers' whose payment_due_date has passed todays date. Below is the following code
CREATE STATEMENT 'Ord'(Order)
CREATE TABLE Ord(OrderID varchar2(9) PRIMARY KEY,
CustomerID varchar(9) REFERENCES Customer(CustomerID),
Expected_Delivery_Date date DEFAULT sysdate NOT NULL,
Actual_Delivery_Date date DEFAULT sysdate NOT NULL,
Payment_Due_Date date DEFAULT sysdate NOT NULL,
Order_Date date DEFAULT sysdate NOT NULL, Price Varchar(10),
Order_Placed varchar2(1) CONSTRAINT OrderPlaced
CHECK(Order_Placed IN('Y','N')) NOT NULL, Order_Confirmed varchar2(1)
CONSTRAINT Order_Confirmed CHECK(Order_Confirmed IN('Y','N'))
NOT NULL, Order_Completed varchar2(1) CONSTRAINT Order_Completed
CHECK(Order_Completed IN('Y','N')) NOT NULL)
INSERT STATEMENT
INSERT INTO Ord VALUES(401565981, 501623129,
'10-Dec-10', '11-Dec-10', '07-Dec-10', '03-Dec-10','£14.99', 'Y', 'Y', 'Y')
CASE STATEMENT
SELECT OrderID, CustomerID, Payment_Due_Date CASE WHEN
Payment_Due_Date = '08-Dec-10' THEN 'Send Final Demand Letter'
ELSE 'Do not send letter'
END FROM Ord;
When I try to run the above case statement I recieve the following error
ORA-00923: FROM keyword not found
where expected
00923. 00000 - "FROM keyword not found where expected"
*Cause:
*Action: Error at Line: 26 Column: 50
Is there any possible way around this?

I think you need a comma between Payment_Due_Date and CASE.

Related

Check constraint for current date and expire date on credit card

Currently learning MariaDB, struggling to add a check constraint for a payments table. I want to check that the inputted expiration date for the credit/debit card is after the current date.
Create table payments (
customerID int(11) Not Null,
debit_credit_Num varchar(20) Not Null,
expireDate date Not Null,
CVS int(3) Not Null,
billaddress varchar(100) Not Null,
billcity varchar(100) Not Null,
billprovince varchar(10) Not Null,
billpostalcode varchar(10) Not Null,
billcountry varchar(100) Not Null,
Constraint fk_has_customerpayment Foreign Key (customerID) References customers(customerID),
Constraint chk_expdate check (date('now') < expireDate);
)
2 errors were found during analysis.
A symbol name was expected! A reserved keyword can not be used as a column name without backquotes. (near "check" at position 463).
Unrecognized statement type. (near "date" at position 470)
MariaDB said:
#1064 - You have an error in your SQL syntax; check the manual that corresponds to your MariaDB server version for the right syntax to use near '' at line 14
Input query sample
Insert into payments (customerID, debit_credit_Num, expireDate, cvs, billAddress, billcity, billprovince, billpostalcode, billcountry) values
(1, '1234 5678 9123 4567', '2025-07-01', 213, '123 Church St', 'Burnaby', 'BC', 'V5A 1S6', 'Canada'),
(2, '0968 1723 2859 1902', '2025-04-01', 874, '321 W Popeyes Dr', 'Vancouver', 'BC', 'V6B 2J2', 'Canada')
(2, '0968 1723 2859 1111', '1999-04-01', 874, '321 W Popeyes Dr', 'Vancouver', 'BC', 'V6B 2J2', 'Canada'); <--- Should fail constraint
Edit 1
Thank you Umut TEKİN, I tried making a trigger like so but I don't know where I went wrong
CREATE TRIGGER chk_expdate
BEFORE INSERT
ON payments
FOR EACH ROW
BEGIN
IF (new.expiredate < CURRENT_DATE) THEN
SIGNAL SQLSTATE '45000'
SET MESSAGE_TEXT = 'Card has expired'; [<------ Line 8]
END IF;
END;
Error Message: MySQL said:
#1064 - You have an error in your SQL syntax; check the manual that corresponds to your MariaDB server version for the right syntax to use near '' at line 8
It works on
https://dbfiddle.uk/?rdbms=mysql_8.0&fiddle=efb986c7edb6b4a3755639e2a380cae4
but not on PHPMyAdmin.
Edit 2
Managed to make trigger work by adding a delimiter on phpmyadmin following Paul T's answer to link
delimiter//
CREATE TRIGGER chk_expdate
BEFORE INSERT ON payments
FOR EACH ROW BEGIN
IF (new.expiredate < CURRENT_DATE) THEN
SIGNAL SQLSTATE '45000'
SET MESSAGE_TEXT = 'Card has expired';
END IF;
END;
You have 2 problem here. First one syntax (missing parenthesis or misplaced semicolon). It should be like this:
Create table payments (
customerID int(11) Not Null,
debit_credit_Num varchar(20) Not Null,
expireDate date Not Null,
CVS int(3) Not Null,
billaddress varchar(100) Not Null,
billcity varchar(100) Not Null,
billprovince varchar(10) Not Null,
billpostalcode varchar(10) Not Null,
billcountry varchar(100) Not Null,
Constraint fk_has_customerpayment Foreign Key (customerID) References customers(customerID),
Constraint chk_expdate check (check condition));
Second one is date(now()) or curdate() are nondeterministic functions. So this usage is not allowed.
Literals, deterministic built-in functions, and operators are
permitted. A function is deterministic if, given the same data in
tables, multiple invocations produce the same result, independently of
the connected user. Examples of functions that are nondeterministic
and fail this definition: CONNECTION_ID(), CURRENT_USER(), NOW().
Reference
Yet, triggers allow you to do that. It' s better also to check here.

SQL Stored Procedure Invalid Identifier

I'm getting ORA-00904 Invalid Identifier for several variables in this stored procedure when trying to compile it in oracle but cannot figure out why; All working storage events are declared at the DECLARE block of the code, and the variables from the schema are all properly defined too.
Has anyone had this error and/or knows how to fix it?
This is the DDL for the schema im working with
CREATE TABLE history
("history_id" number(4) primary key,
"history_dt" date not null,
"history_time" timestamp not null,
"booking_cost" varchar2(50) not null,
"booking_status" varchar2(50) not null
);
CREATE TABLE attendees
("attendee_id" number(8) primary key,
"attendee_name" varchar2(50) not null,
"attendee_class" number(4) not null,
"attendee_school" varchar2(50) not null,
"attendee_status" varchar2(50) not null
);
CREATE TABLE event
("event_id" number(10) primary key,
"event_name" varchar2(100) not null,
"event_location" varchar2(100) not null,
"event_size" number(4) not null,
"start_dt" date not null,
"end_dt" date not null,
"class_restriction" number(4) not null,
"school_restriction" varchar2(100) not null
);
CREATE TABLE reservation
("reservation_id" number(3) primary key,
"event" number(10) references event("event_id"),
"attendee" number(8) references attendees("attendee_id"),
"booking" number(4) references history("history_id"),
"reservation_status" varchar2(50) not null
);
These are the error messages I'm getting
Compilation failed,line 19 (15:38:10)
PL/SQL: ORA-00904: "END_DT": invalid identifierCompilation failed,line 18 (15:38:10)
PL/SQL: SQL Statement ignoredCompilation failed,line 26 (15:38:10)
PLS-00302: component 'EVENT_ID' must be declaredCompilation failed,line 26 (15:38:10)
PL/SQL: ORA-00904: "RESERVATION"."EVENT_ID": invalid identifierCompilation failed,line 26 (15:38:10)
PL/SQL: SQL Statement ignoredCompilation failed,line 36 (15:38:10)
PL/SQL: ORA-00904: "EVENT_ID": invalid identifierCompilation failed,line 35 (15:38:10)
PL/SQL: Statement ignoredCompilation failed,line 51 (15:38:10)
PL/SQL: ORA-00947: not enough valuesCompilation failed,line 51 (15:38:10)
create or replace procedure Event_Planning
(arg_event_id in number, arg_student_id in number)
IS
ws_event_name varchar(100);
ws_capacity number;
ws_event_school varchar2(4);
ws_event_class number;
past_event exception;
capacity exception;
school exception;
class exception;
BEGIN
--Test for active event
select max(event_name) into ws_event_name from event
where event_id = arg_event_id and end_dt > SYSDATE;
if ws_event_name is null
then raise past_event;
end if;
--Test for capacity
select max(event_capacity) into ws_capacity from event JOIN reservation ON event.event_id = reservation.event_id
where event_id = arg_event
and event_capacity > reservation_size;
if ws_capacity is null
then raise capacity;
end if;
--Test for restricted school
select max(school_restriction) into ws_event_school from event
where event_id = arg_event_id;
if ws_event_school = arg_school
then raise school;
end if;
--Test for restricted class
select max(class_restriction) into ws_event_class from event
where event.id = arg_event;
if ws_event_class = arg_class
then raise class;
end if;
--Update reservation table
insert into reservation values
(Seq.nextval, arg_event, arg_student);
update reservation
set reservation_size = reservation_size + 1;
--Exceptions
Exception
when past_event
then raise_application_error(-20001, 'Event has passed');
when capacity
then raise_application_error(-20002, 'Event at capacity');
when school
then raise_application_error(-20003, 'Invalid school');
when class
then raise_application_error(-20004, 'Invalid class');
END;
To make it more likely to have your questions answered, share everything.
That includes, the actual error messages. And if you REALLY want to be nice, include the TABLE DDL (and even some data) for your EVENT and RESERVATION tables.
I was too 'lazy' to guess what yours looked like, and just changed your queries to dummy tables to replicate the issue.
You haven't declared
ws_school
arg_school
ws_class
arg_class
When you compile, the compiler will return the line number and curpos of your issue. You're referring to things the db doesn't know about.
Recommendations
Don't hard code the data type definitions for your variables. Because, tables CAN and WILL change.
Instead, make them dynamic.
So, instead of saying
WS_SCHOOL VARCHAR2(4);
do something like
WS_SCHOOL TABLE.COLUMN%TYPE;
Then when your tables change, your code won't necessarily break.
By default, Oracle identifiers such as table and column names are case-insensitive, so for example you can
select dummy, DUMMY, Dummy
from dual;
However, double-quoting is also available to allow you to override the standard rules if you really need to:
create table demo("123/Wow!" number);
SQL> desc demo
Name Null? Type
----------------------------------------- -------- ----------------------------
123/Wow! NUMBER
Your tables history, attendees, event etc have case-sensitive, lowercase column names due to the double quoting, so you have to follow the same convention whenever you use them:
SQL> select count(event_id) from event;
select count(event_id) from event
*
ERROR at line 1:
ORA-00904: "EVENT_ID": invalid identifier
SQL> select count("event_id") from event;
COUNT("EVENT_ID")
-----------------
0
1 row selected.
Unless there is some important reason to do this, it would be simplest to recreate the tables without double-quoted column names.
(Also, reservation has an "event" column, not "event_id". There may be other typos like this - I haven't checked the whole thing.)
That doesn't need to use end_date on filters, because event_id is a primary key.
select "event_name" into ws_event_name
from event
where "event_id" = arg_event_id;
That looks so confuse to know, where the following columns come from: ---=^^^=---
-- event_capacity
-- reservation_size
select max("event_size") into ws_capacity
from event
join reservation
on event."event_id" = reservation."event"
where "event_id" = arg_event_id
and "event_size" > count("reservation_id");
Syntax error for event.id, it must event_id
select "class_restriction" into ws_event_class
from event
where "event_id" = arg_event_id;
Insert into reservation table:
select count(*) into reserve_count
from reservation
where "event" = arg_event_id
and "attendee" = arg_studen_id;
if reserve_count = 0
then
insert into reservation values
(Seq.nextval, arg_event_id, arg_student_id, null, "R");
end if;
--- note: that needs to declare reserve_count
Use count() to populate attendees, then no need to update reservation table.
-- update reservation
-- set reservation_size = reservation_size + 1;
reservation table:
CREATE TABLE reservation
("reservation_id" number(13) primary key,
"event" number(10) references event("event_id"),
"attendee" number(8) references attendees("attendee_id"),
"booking" number(10) references history("history_id"),
"reservation_status" varchar(1) not null
);
To merge as a single query:
select count(*), "event_name", "class_restriction"
into event_count, ws_event_name, ws_event_class
from event
where "event_id" = arg_event_id;
-- note: that needs to declare event_count

SQL : can not create a table

I do the following:
use oracle developer
create table loan
(
barcode number (20) not null ,
borrowernumber number (7) ,
loancurrentdate date ,
loanreturndate date ,
loanreserveorder number (20) ,
paymentdate date ,
borrower_borrowernumber number not null
);
alter table loan add constraint loan_pk primary key (barcode) ;
Cannot create a table, then change it ...
create table loan
(
loanno INT not null,
loandate date not null,
loanreturndate date null,
loanreserve number (20) null,
paymentdate date null,
);
alter table loan add constraint loan_pk primary key (loanno) ;
I get the following error. Why am I getting this?
Error report
SQL Error: ORA-00942: table or view does not exist
00942. 00000 - "table or view does not exist"
It also shows "invalid identifier"
Error report:
SQL Error: ORA-00904: : invalid identifier
00904. 00000 - "%s: invalid identifier"
Or should I delete paymentdate?
After delete the wrong comma, the table created.
Both examples you posted are correct (apart from that superfluous comma at the end of the second CREATE TABLE statement). This are SQL*Plus examples, but - as SQL Developer emulates it well, I believe that they should work just fine there too.
The first one:
SQL> create table loan
2 (
3 barcode number (20) not null ,
4 borrowernumber number (7) ,
5 loancurrentdate date ,
6 loanreturndate date ,
7 loanreserveorder number (20) ,
8 paymentdate date ,
9 borrower_borrowernumber number not null
10 );
Table created.
SQL> alter table loan add constraint loan_pk primary key (barcode) ;
Table altered.
The second one:
SQL> drop table loan;
Table dropped.
SQL> create table loan
2 (
3 loanno INT not null,
4 loandate date not null,
5 loanreturndate date null,
6 loanreserve number (20) null,
7 paymentdate date null
8 );
Table created.
SQL> alter table loan add constraint loan_pk primary key (loanno) ;
Table altered.
SQL>
What do you exactly mean by saying "Cannot create a table, then change it ..." after the first CREATE TABLE? Any error? If so, which one?
"ORA-00942: table or view does not exist" is probably raised by ALTER TABLE as you can't alter it if it doesn't exist (but the mystery is why you can't create it).
"ORA-00904: : invalid identifier" means that you used a column name which doesn't exist in the table, such as
SQL> alter table loan modify xxx number;
alter table loan modify xxx number
*
ERROR at line 1:
ORA-00904: "XXX": invalid identifier
If possible, do the same as I did - copy/paste SQL*Plus session so that we could see what you did and how Oracle responded.
This should work
drop table loan;
create table loan
(
loanno INT not null,
loandate date not null,
loanreturndate date null,
loanreserve number (20) null,
paymentdate date null
);

"Not a valid month" or number

Getting this error while trying to put a few inserts into a table.
Getting an error regarding not a valid month and when I try change it around i'm getting invalid number error.
ORA-01843: not a valid month ORA-06512: at "SYS.DBMS_SQL"
Code:
CREATE TABLE ExpenseReport (
ERNo NUMERIC(10) NOT NULL,
ERDesc VARCHAR(255) NOT NULL,
ERSubmitDate DATE DEFAULT CURRENT_TIMESTAMP,
ERStatusDate DATE NOT NULL,
ERStatus VARCHAR(8) DEFAULT 'PENDING',
SubmitUserNo NUMERIC(10) NOT NULL,
ApprUserNo NUMERIC(10) NOT NULL,
CONSTRAINT ExpenseReport_CK1 CHECK (ERStatusDate >= ERSubmitDate),
CONSTRAINT ExpenseReport_CK2 CHECK (ERStatus = 'PENDING'/'APPROVED'/'DENIED'),
CONSTRAINT ExpenseReport_PK1 PRIMARY KEY(ERNo),
CONSTRAINT ExpenseReport_FK1 FOREIGN KEY(SubmitUserNo) REFERENCES Users(UserNo),
CONSTRAINT ExpenseReport_FK2 FOREIGN KEY(ApprUserNo) REFERENCES (USerNo)
);
INSERT INTO ExpenseReport
(ERNo, ERDesc, ERSubmitDate, ERStatusDate, ERStatus, SubmitUserNo, ApprUSerNo)
VALUES (1,'Sales Presentation','8/10/2002','8/26/2002','APPROVED',3,4);
I've also tried using the TO_DATE but having no luck there,
by any chance can anyone see where i'm going wrong.
Use the DATE keyword and standard date formats:
INSERT INTO ExpenseReport (ERNo, ERDesc, ERSubmitDate, ERStatusDate, ERStatus, SubmitUserNo, ApprUSerNo)
VALUES (1, 'Sales Presentation', DATE '2001-08-10', DATE '2001-08-2006', 'APPROVED', 3, 4);
In addition to the satisfaction of using standard date formats, this protects you against changes in local settings.
In your DDL statement:
CONSTRAINT ExpenseReport_CK2 CHECK (ERStatus = 'PENDING'/'APPROVED'/'DENIED')
Should be:
CONSTRAINT ExpenseReport_CK2 CHECK (ERStatus IN ( 'PENDING', 'APPROVED', 'DENIED' ) )
When you are trying to insert values the check constraint is being evaluated and it is trying to perform a division operation on the three string values'PENDING'/'APPROVED'/'DENIED' which results in ORA-01722: invalid number.
Once you change this then using TO_DATE('01/01/02','DD/MM/YY') (as you wrote in comments) or an ANSI date literal DATE '2002-01-01' should work in your DML statements.
(Note: Be careful using 2-digit years or you can find that dates are inserted with the wrong century.)
Check your date format: select sysdate from dual;
and enter as it show. OR
change your date format: alter session set nls_date_format= 'DD-Mon-YYYY HH24:MI:SS';
It Was Easy :
if Your code Like This just remove hem and write that
Example :
Your code : values ('30178','K111', '22/12/2008')
Do This : values ('30178','K111', '22/Dec/2008')

ORA-001722 Invalid Number when insert in Oracle SQL

CREATE TABLE the_user( Name VARCHAR(40) not null,
Address VARCHAR(255) not null,
Delivery_address VARCHAR(255),
Email VARCHAR(25) not null,
Phone INTEGER not null,
Status INTEGER not null,
Password VARCHAR(25) not null,
DOB DATE not null,
PRIMARY KEY (Email),
FOREIGN KEY (Status) REFERENCES User_Status (Status_Id),
CONSTRAINT check_Password CHECK (Password > 4)
);
INSERT INTO the_user VALUES (
'Pergrin Took',
'12 Bag end, hobbiton, The Shire, Eriador',
'The address, Dublin',
'ptook#lotr.com',
'8679046',
'001',
'treebeard',
TO_DATE('2013/11/04 14:11:34', 'yyyy/mm/dd hh24:mi:ss')
);
I have the above database in Oracle but when I try to run the insert command I get an ORA-1722 error, Invalid Number. There is a entry in the user_status table which corresponds to the 1 in the insert.
I have been stuck on this for days.
Quotes are not a problem - it will be converted implicitly to numbers as far as they are valid.
Check your constraints:
CONSTRAINT check_Password CHECK (Password > 4)
Here you try to compare string and number -> in this comparison Oracle always tries to cast both as numbers -> password fails and you see an error.
Try to use instead of password e.g. '55' and you will see the row is inserted.
Perhaps you wanted to do this?
CONSTRAINT check_Password CHECK (length(Password) > 4)