How can i restrict field in a table to 15 or 16 digits. I have this table:
create table Person(
,UserID varchar(30)
,Password varchar(30) not null
,CCtype varchar(8)
,CCNumber numeric
,primary key(UserID)
,constraint CK_CCvalidity check
(
(CCType is null or CCNumber is null)
or
(
(CCType = 'Amex' or CCType = 'Discover' or CCType = 'MC' or CCType = 'VISA')
and
(CCNumber >= 15 and CCNumber <= 16)
)
)
);
But this actually checks for the values 15 an 16, not for the number of digits. Also, we can assume that the numeric may hold 000... as the first digits.
Thanks for the help
CCNumber should never be numeric. That will lead to a world of pain.
It should be varchar(X) where X is 13 - 24 digits.
Credit card numbers are usually represented by groups of 4 or 5
digits separated by spaces or dashes or simply all together with no separators.
[note: American Express: 15 digits; Visa: 13 or 16 digits]
In response to your comment:
ALTER TABLE dbo.Person
ADD CONSTRAINT CK_Person_CCNumber
CHECK (LEN(CCNumber) = 16 OR LEN(CCNumber) = 15);
But probably better as:
ALTER TABLE dbo.Person
ADD CONSTRAINT CK_Person_CCNumber
CHECK (LEN(CCNumber) >= 13 AND LEN(CCNumber) <= 15);
AND add a constraint to ensure it is a valid credit card number perhaps (there are plenty of examples online).
Bank Card Number
You can create a function to remove the Non-Numeric characters from a varchar, like this one:
CREATE Function [fnRemoveNonNumericCharacters](#strText VARCHAR(1000))
RETURNS VARCHAR(1000)
AS
BEGIN
WHILE PATINDEX('%[^0-9]%', #strText) > 0
BEGIN
SET #strText = STUFF(#strText, PATINDEX('%[^0-9]%', #strText), 1, '')
END
RETURN #strText
END
Now, if you want to allow only digits and want to check the length, you could add two Check Constraints like this:
Create Table Person
(
Id int not null primary key,
CCNumber varchar(30),
CONSTRAINT CK_Person_CCNumber_Length CHECK (LEN(CCNumber) BETWEEN 15 AND 16),
CONSTRAINT CK_Person_CCNumber_IsNumeric CHECK (LEN(dbo.[fnRemoveNonNumericCharacters](CCNumber)) = LEN(CCNumber))
)
First Constraint will check the length of the field to be 15 or 16.
Second one will check that the field is numeric (length of field removing non-numeric is equal to length of the original field)
You can also do it in just one ANDed Check Constraint.
Storing a credit card number as a...number is guaranteed to shoot you in the foot some day. Such as the day you start encountering credit card numbers with leading zeroes. They may consist of decimal digits, but they're not numbers. They're text.
Plan for the future: what happens when somebody start issuing credit card numbers with letters?
So, try this:
create table dbo.some_table
(
...
credit_card_type varchar(8) null ,
credit_card_number varchar(32) null ,
constraint some_table_ck01 check (
( credit_card_type is not null
and credit_card_number is not null
)
OR ( credit_card_type is null
and credit_card_number is null
)
) ,
constraint some_table_ck02 check (
credit_card_type in ( 'amex' , 'discover' , 'mc' , 'visa' )
) ,
constraint some_table_ck03 check (
credit_card_number not like '%[^0-9]%'
) ,
constraint some_table_ck04 check (
len(credit_card_number) = case credit_card_type
when 'amex' then 15
when 'discover' then 16
when 'mc' then 16
when 'visa' then 16
else -1 -- coerce failure on invalid/unknown type
end
) ,
)
go
insert some_table values( null , null ) -- succeeds
insert some_table values( 'amex' , null ) -- violates check constraint #1
insert some_table values( null , '1' ) -- violates check constraint #1
insert some_table values( 'acme' , '1' ) -- violates check constraint #2
insert some_table values( 'amex' , 'A1B2' ) -- violates check constraint #3
insert some_table values( 'amex' , '12345' ) -- violates check constraint #4
insert some_table values( 'amex' , '123456789012345' ) -- success!
go
But as noted by others, you need to fix your data model. A credit card is a separate entity from a customer. It has a dependent relationship upon the customer (the card's existence is predicated upon the existence of the customer who own it). You can a data model like the following. This
create table credit_card_type
(
int id not null primary key clustered ,
description varchar(32) not null unique ,
... -- other columns describing validation rules here
)
create table credit_card
(
customer_id int not null ,
type int not null ,
number varchar(32) not null ,
expiry_date date not null ,
primary key ( customer_id , number , type , expiry_date ) ,
unique ( number , customer_id , type , expiry_date ) ,
foreign key customer references customer(id) ,
foreign key type references credit_card_type(id) ,
)
Further: you are encrypting card numbers using strong encryption, aren't you?
Related
Could someone help me here? I'm trying to create a trigger that updates balance in ACCOUNT table after transactions from the TRANSFERS table. The whole table model is bigger, but here are two of them:
--ACCOUNT--
CREATE TABLE account(
account_num NUMBER(8) NOT NULL PRIMARY KEY,
ktnr REFERENCES account_type(ktnr),
regdate DATE NOT NULL,
balance NUMBER(10,2));
--TRANSFERS--
CREATE TABLE transfers(
row_nr NUMBER(9) NOT NULL PRIMARY KEY,
pers_nr REFERENCES customer(pers_nr),
from_account_num REFERENCES account(account_num),
to_account_num REFERENCES account(account_num),
amount NUMBER(10,2),
date DATE NOT NULL);
And the code I think is quite wrong but that's the idea of solution. Not sure how to write it in a better way.
create or replace trigger aifer_transfers
after insert
on transfers
for each row
when (new.amount is not null)
begin
if :new.to_account_num != :new.pers_nr then
update account a
set a.balance = a.balance - :new.amount
where :old.account_num = :new:account_num;
elsif
:new.to_account_num = :new.pers_nr then
update account a
set a.balance = a.balance + :new.amount
where :old.account_num = :new:account_num;
end if;
end;
Many different errors, depending on chosen variables:
Line/Col: 3/9 PL/SQL: SQL Statement ignored
Line/Col: 5/26 PLS-00049: bad bind variable 'NEW'
Your table declarations are missing some data types (since we don't have your other tables) and, from Oracle 12, you can use IDENTITY columns for the primary keys (and have some CHECK constraints and DEFAULT values for DATE columns):
CREATE TABLE account(
account_num NUMBER(8,0)
GENERATED ALWAYS AS IDENTITY
NOT NULL
CONSTRAINT account__account_num__pk PRIMARY KEY,
ktnr NUMBER(8,0)
-- CONSTRAINT account__ktnr__fk REFERENCES account_type(ktnr)
,
regdate DATE
DEFAULT SYSDATE
NOT NULL,
balance NUMBER(10,2)
NOT NULL
);
CREATE TABLE transfers(
row_nr NUMBER(9)
GENERATED ALWAYS AS IDENTITY
NOT NULL
CONSTRAINT transfers__row_nr__pk PRIMARY KEY,
pers_nr NUMBER(8,0)
NOT NULL
-- CONSTRAINT transfers__pers_nr__fk REFERENCES customer(pers_nr)
,
from_account_num NOT NULL
CONSTRAINT transfers_from__fk REFERENCES account(account_num),
to_account_num NOT NULL
CONSTRAINT transfers__to__fk REFERENCES account(account_num),
amount NUMBER(10,2)
NOT NULL
CONSTRAINT transfers__amount_chk CHECK ( amount > 0 ),
datetime DATE
DEFAULT SYSDATE
NOT NULL,
CONSTRAINT transfers__from_ne_to__chk CHECK ( from_account_num != to_account_num )
);
Then you can create the trigger:
CREATE TRIGGER aifer_transfers
AFTER INSERT ON TRANSFERS
FOR EACH ROW
BEGIN
UPDATE account
SET balance = CASE account_num
WHEN :NEW.from_account_num
THEN balance - :NEW.amount
WHEN :NEW.to_account_num
THEN balance + :NEW.amount
ELSE balance
END
WHERE account_num IN ( :new.from_account_num, :new.to_account_num );
END;
/
If you create 3 accounts:
INSERT INTO account ( ktnr, balance ) VALUES ( 0, 100 );
INSERT INTO account ( ktnr, balance ) VALUES ( 0, 100 );
INSERT INTO account ( ktnr, balance ) VALUES ( 0, 100 );
Then after:
INSERT INTO transfers (
pers_nr, from_account_num, to_account_num, amount
) VALUES (
0, 1, 2, 20
);
Then:
SELECT * FROM account;
Outputs:
ACCOUNT_NUM
KTNR
REGDATE
BALANCE
1
0
18-MAY-21
80
2
0
18-MAY-21
120
3
0
18-MAY-21
100
Then after:
INSERT INTO transfers (
pers_nr, from_account_num, to_account_num, amount
) VALUES (
0, 1, 3, 15
);
It would be:
ACCOUNT_NUM
KTNR
REGDATE
BALANCE
1
0
18-MAY-21
65
2
0
18-MAY-21
120
3
0
18-MAY-21
115
Then after:
INSERT INTO transfers ( pers_nr, from_account_num, to_account_num, amount )
SELECT 0, 3, 2, 10 FROM DUAL UNION ALL
SELECT 0, 2, 3, 20 FROM DUAL UNION ALL
SELECT 0, 1, 2, 10 FROM DUAL;
It would be:
ACCOUNT_NUM
KTNR
REGDATE
BALANCE
1
0
18-MAY-21
55
2
0
18-MAY-21
120
3
0
18-MAY-21
125
db<>fiddle here
Update
For your tables, without any additional CHECK constraints, you may want:
CREATE TRIGGER aifer_transfers
AFTER INSERT ON TRANSFERS
FOR EACH ROW
BEGIN
IF :NEW.amount <= 0 THEN
RAISE_APPLICATION_ERROR( -20000, 'Amount must be above zero.' );
END IF;
IF :NEW.from_account_num IS NULL THEN
RAISE_APPLICATION_ERROR( -20000, 'From account must be non-null.' );
END IF;
IF :NEW.to_account_num IS NULL THEN
RAISE_APPLICATION_ERROR( -20000, 'To account must be non-null.' );
END IF;
IF :NEW.from_account_num = :NEW.to_account_num THEN
RAISE_APPLICATION_ERROR( -20000, 'Accounts must be different.' );
END IF;
UPDATE account
SET balance = CASE account_num
WHEN :NEW.from_account_num
THEN balance - :NEW.amount
WHEN :NEW.to_account_num
THEN balance + :NEW.amount
ELSE balance
END
WHERE account_num IN ( :new.from_account_num, :new.to_account_num );
END;
/
(But that validation should all be implemented as CHECK constraints on the transfers table rather than in a trigger.)
db<>fiddle here
CREATE OR REPLACE TRIGGER EVALUATION
BEFORE INSERT OR UPDATE OR DELETE ON BOOKING
FOR EACH ROW
DECLARE
BEGIN
SELECT BOOKING_EVALUATION FROM BOOKING WHERE BOOKING_EVALUATION > 2;
SELECT BOOKING_EVALUATION INTO EVALUATIONAUDIT FROM BOOKING;
IF INSERTING THEN
INSERT INTO EVALUATIONAUDIT (VOYAGES_ID,CUSTOMER_NAME,START_DATE,SHIP_NAME,BOOKING_EVALUATION)
VALUES(:NEW.VOYAGES_ID,:NEW.CUSTOMER_NAME,:NEW.START_DATE,:NEW.SHIP_NAME,:NEW.BOOKING_EVALUATION);
END IF;
IF UPDATING THEN
INSERT INTO EVALUATIONAUDIT (VOYAGES_ID,CUSTOMER_NAME,START_DATE,SHIP_NAME,BOOKING_EVALUATION)
VALUES(:OLD.VOYAGES_ID,:OLD.CUSTOMER_NAME,:OLD.START_DATE,:OLD.SHIP_NAME,:OLD.BOOKING_EVALUATION);
END IF;
IF DELETING THEN
INSERT INTO EVALUATIONAUDIT (VOYAGES_ID,CUSTOMER_NAME,START_DATE,SHIP_NAME,BOOKING_EVALUATION)
VALUES(:OLD.VOYAGES_ID,:OLD.CUSTOMER_NAME,:OLD.START_DATE,:OLD.SHIP_NAME,:OLD.BOOKING_EVALUATION);
END IF;
END;
This is my audit table:
desc evaluationaudit;
Name Null? Type
----------------------------------------- -------- -----------------------
AUDITT_ID NOT NULL NUMBER(10)
VOYAGES_ID NOT NULL NUMBER(10)
CUSTOMER_NAME NOT NULL VARCHAR2(20)
START_DATE NOT NULL DATE
SHIP_NAME NOT NULL VARCHAR2(20)
BOOKING_EVALUATION NOT NULL NUMBER(20)
and this is my show error output:
SQL> SHOW ERRORS;
Errors for TRIGGER EVALUATION:
LINE/COL ERROR
-------- -------------------------------------------------------------
12/24 PLS-00049: bad bind variable 'NEW.CUSTOMER_NAME'
12/43 PLS-00049: bad bind variable 'NEW.START_DATE'
12/59 PLS-00049: bad bind variable 'NEW.SHIP_NAME'
18/24 PLS-00049: bad bind variable 'OLD.CUSTOMER_NAME'
18/43 PLS-00049: bad bind variable 'OLD.START_DATE'
18/59 PLS-00049: bad bind variable 'OLD.SHIP_NAME'
24/24 PLS-00049: bad bind variable 'OLD.CUSTOMER_NAME'
24/43 PLS-00049: bad bind variable 'OLD.START_DATE'
24/59 PLS-00049: bad bind variable 'OLD.SHIP_NAME'
I wanted to add to the audit table. If a customer gives a poor evaluation of 2 or less, the details of their voyage (customer_name, name and date of the cruise, ship name and evaluation) but I'm getting error
Warning: Trigger created with compilation errors.
And the audit table is empty, showing no rows selected. I can't seem to find the problem where I am going wrong.
Maybe the following code snippets will help you. Suppose we have 2 tables: BOOKING, and EVALUATION_AUDIT (everything written in uppercase letters is taken from the code in your question).
Tables
create table booking (
VOYAGES_ID number primary key
, CUSTOMER_NAME VARCHAR2(20) NOT NULL
, START_DATE DATE NOT NULL
, SHIP_NAME VARCHAR2(20) NOT NULL
, BOOKING_EVALUATION NUMBER(20) NOT NULL
) ;
create table evaluationaudit (
AUDITT_ID number generated always as identity start with 5000 primary key
, trg_cond_pred varchar2( 64 ) default 'Row not added by evaluation trigger!'
, VOYAGES_ID NUMBER(10) NOT NULL
, CUSTOMER_NAME VARCHAR2(20) NOT NULL
, START_DATE DATE NOT NULL
, SHIP_NAME VARCHAR2(20) NOT NULL
, BOOKING_EVALUATION NUMBER(20) NOT NULL
) ;
Trigger
-- "updating" and "deleting" code omitted for clarity
CREATE OR REPLACE TRIGGER EVALUATION_trigger
BEFORE INSERT OR UPDATE OR DELETE ON BOOKING
FOR EACH ROW
BEGIN
case
when INSERTING then
if :new.booking_evaluation <= 2 then
INSERT INTO EVALUATIONAUDIT
( trg_cond_pred,
VOYAGES_ID, CUSTOMER_NAME, START_DATE, SHIP_NAME, BOOKING_EVALUATION )
VALUES (
'INSERTING'
, :NEW.VOYAGES_ID
, :NEW.CUSTOMER_NAME
, :NEW.START_DATE
, :NEW.SHIP_NAME
, :NEW.BOOKING_EVALUATION
);
end if ;
end case ;
END ;
/
Testing
One of your requirements (in your question) is:
I wanted to add to the audit table. If a customer gives a poor
evaluation of 2 or less, the details of their voyage (customer_name,
name and date of the cruise, ship name and evaluation)
delete from evaluationaudit ;
delete from booking ;
-- booking_evaluation greater than 2 -> no entry in audit table
insert into booking
( VOYAGES_ID, CUSTOMER_NAME, START_DATE, SHIP_NAME, BOOKING_EVALUATION )
values ( 1111, 'customer1', date '2018-05-24', 'ship1', 9999 ) ;
select * from evaluationaudit ;
-- no rows selected
-- booking_evalution = 2 -> insert a row into the audit table
insert into booking
( VOYAGES_ID, CUSTOMER_NAME, START_DATE, SHIP_NAME, BOOKING_EVALUATION )
values ( 1112, 'customer1', date '2018-05-24', 'ship1', 2 ) ;
select * from evaluationaudit ;
AUDITT_ID TRG_COND_PRED VOYAGES_ID CUSTOMER_NAME START_DATE SHIP_NAME BOOKING_EVALUATION
5000 INSERTING 1112 customer1 24-MAY-18 ship1 2
__Update__
If - as you wrote in your comment - you need to pull in some more data from other tables, maybe you want to try the following approach: keep the trigger code rather brief, and use it to call a procedure for the more complicated stuff eg
Tables
create table evaluationaudit (
AUDITT_ID number generated always as identity start with 7000 primary key
, trg_cond_pred varchar2( 64 ) default 'Row not added by evaluation trigger!'
, VOYAGES_ID NUMBER NOT NULL
, CUSTOMER_NAME VARCHAR2(20) NOT NULL
, SHIP_NAME VARCHAR2(20) NOT NULL
, BOOKING_EVALUATION NUMBER(20) NOT NULL
) ;
create table ships ( name varchar2( 64 ), id number unique ) ;
create table customers ( name varchar2( 64 ), id number unique ) ;
insert into ships ( name, id ) values ( 'ship1', 501 );
insert into ships ( name, id ) values ( 'ship2', 502 );
insert into ships ( name, id ) values ( 'ship3', 503 );
insert into customers ( name, id ) values ( 'customer1', 771 ) ;
insert into customers ( name, id ) values ( 'customer2', 772 ) ;
insert into customers ( name, id ) values ( 'customer3', 773 ) ;
create table bookings (
id number generated always as identity start with 5000 primary key
, voyagesid number
, shipid number
, customerid number
, evaluation number
, bookingdate date
);
Trigger
create or replace trigger bookingeval
before insert on bookings
for each row
when ( new.evaluation <= 2 ) -- Use NEW without colon here! ( see documentation )
begin
auditproc( :new.voyagesid, :new.customerid, :new.shipid, :new.evaluation ) ;
end ;
/
Procedure
create or replace procedure auditproc (
voyagesid_ number
, customerid_ number
, shipid_ number
, evaluation_ number
)
as
customername varchar2( 64 ) := '' ;
shipname varchar2( 64 ) := '' ;
begin
-- need to find the customername and shipname before INSERT
select name into customername from customers where id = customerid_ ;
select name into shipname from ships where id = shipid_ ;
insert into evaluationaudit
( trg_cond_pred,
voyages_id, customer_name, ship_name, booking_evaluation )
values (
'INSERTING'
, voyagesid_
, customername
, shipname
, evaluation_
);
end ;
/
Testing
-- evaluation > 2 -> no INSERT into evaluationaudit
insert into bookings
( voyagesid, customerid, shipid, evaluation, bookingdate )
values ( 1111, 771, 501, 9999, sysdate ) ;
select * from evaluationaudit ;
-- no rows selected
-- evaluation = 2
-- -> trigger calling audit procedure -> inserts into evaluationaudit
insert into bookings
( voyagesid, customerid, shipid, evaluation, bookingdate )
values ( 1112, 772, 502, 2, sysdate ) ;
select * from evaluationaudit ;
AUDITT_ID TRG_COND_PRED VOYAGES_ID CUSTOMER_NAME SHIP_NAME BOOKING_EVALUATION
7000 INSERTING 1112 customer2 ship2 2
To preface this, I have 3 tables, there is table
Product
- id
- name
- availability
Then is has 2 child tables:
Tables
- id
- product_id (foreign key to product(id))
- size
Chairs
- id
- product_id (foreign key to product(id))
- color
What I want to do is everytime I insert a new record into the chairs/tables table, I want to check whether it is not already contained in one of them. Or in other words, one product cannot be chair and table at once. How do I do this?
Thank you.
You could use a CHECK constraint for this, which, in combination with some other constraints, may give you the required behaviour. There are some restrictions on check constraints, one of them being:
The condition of a check constraint can refer to any column in the
table, but it cannot refer to columns of other tables.
( see the documentation )
In the following example, the ID columns "chairs.id" and "tables.id" have been moved into the "products" table, which contains the CHECK constraint. The UNIQUE constraints enforce a one-to-one relationship as it were ( allowing only one value for each of the REFERENCED ids ). The DDL code looks a bit busy, but here goes:
Tables
create table products (
id number generated always as identity primary key
, name varchar2(128)
, availability varchar2(32)
);
-- product_id removed
create table tables (
id number primary key
, size_ number
) ;
-- product_id removed
create table chairs (
id number primary key
, color varchar2(32)
);
Additional columns and constraints
alter table products
add (
table_id number unique
, chair_id number unique
, check (
( table_id is not null and chair_id is null )
or
( table_id is null and chair_id is not null )
)
);
alter table tables
add constraint fkey_table
foreign key ( id ) references products ( table_id ) ;
alter table chairs
add constraint fkey_chairs
foreign key ( id ) references products ( chair_id ) ;
Testing
-- {1} Add a chair: the chair_id must exist in PRODUCTS.
insert into chairs ( id, color ) values ( 1000, 'maroon' ) ;
-- ORA-02291: integrity constraint ... violated - parent key not found
-- Each chair needs an entry in PRODUCTS first:
insert into products ( name, availability, chair_id )
values ( 'this is a chair', 'in stock', 1000 ) ;
insert into chairs ( id, color ) values ( 1000, 'maroon' ) ;
-- okay
-- {2} We cannot add another chair that has the same chair_id. Good.
insert into products ( chair_id ) values ( 1000 ) ;
-- ORA-00001: unique constraint ... violated
-- {3} Add a table.
insert into products ( name, availability, table_id )
values ( 'this is a table', 'unavailable', 1000 ) ;
-- okay
insert into tables ( id, size_ ) values ( 1000, 60 ) ;
-- {4} Is it possible to add another table, with the same table_id? No. Good.
insert into tables ( id, size_ ) values ( 1000, 60 ) ;
-- ORA-00001: unique constraint ... violated
insert into products ( name, availability, table_id )
values ('this is a table', 'unavailable', 1000 ) ;
-- ORA-00001: unique constraint ... violated
-- {5} We cannot add something that is a chair _and_ a table (at the same time).
insert into products ( name, availability, table_id, chair_id )
values ( 'hybrid', 'awaiting delivery', 2000, 2000 ) ;
-- ORA-02290: check constraint ... violated
Resultset
SQL> select * from products;
ID NAME AVAILABILITY TABLE_ID CHAIR_ID
21 this is a chair in stock NULL 1000
23 this is a table unavailable 1000 NULL
NOTE: The product ID (NOT the table_id or the chair_id) "identifies" a particular table/chair. The values in the TABLE_ID and CHAIR_ID columns are only used to "link" to the (unique) IDs in the child table(s).
Alternative: object-relational approach.
This solution may be more suitable for solving the problem. Here, we create a supertype (product_t) first, and then 2 subtypes (chair_t and table_t, respectively). This allows us to create a table PRODUCTS_, using product_t for storing the data we need.
Types and table
create or replace type product_t as object (
name varchar2(64)
, availability varchar2(64)
)
not final;
/
create or replace type chair_t under product_t (
color varchar2(64)
)
/
create or replace type table_t under product_t (
size_ number
)
/
create table products_ (
id number generated always as identity primary key
, product product_t
);
Testing
-- "standard" INSERTs
begin
insert into products_ ( product )
values ( chair_t( 'this is a chair', 'in stock', 'maroon' ) );
insert into products_ ( product )
values ( table_t( 'this is a table', 'not available', 60 ) );
end;
/
-- unknown types cannot be inserted
insert into products_ ( product )
values ( unknown_t( 'type unknown!', 'not available', 999 ) );
-- ORA-00904: "UNKNOWN_T": invalid identifier
insert into products_ ( product )
values ( product_t( 'supertype', 'not available', 999 ) );
-- ORA-02315: incorrect number of arguments for default constructor
-- object of SUPERtype can be inserted
insert into products_ ( product )
values ( product_t( 'supertype', 'not available' ) );
-- 1 row inserted.
Query
select
id
, treat( product as table_t ).name as name_of_table
, treat( product as chair_t ).name as name_of_chair
, case
when treat( product as table_t ) is not null
then 'TABLE_T'
when treat( product as chair_t ) is not null
then 'CHAIR_T'
when treat( product as product_t ) is not null
then 'PRODUCT_T'
else
'TYPE unknown :-|'
end which_type_is_it
from products_ ;
-- result
ID NAME_OF_TABLE NAME_OF_CHAIR WHICH_TYPE_IS_IT
1 NULL this is a chair CHAIR_T
2 this is a table NULL TABLE_T
3 NULL NULL PRODUCT_T -- neither a chair nor a table ...
CREATE TABLE customer (
customer_id INT NOT NULL generated always AS identity(start WITH 1, increment BY 1) CONSTRAINT customers_pk PRIMARY KEY
,cFirstname VARCHAR(20) NOT NULL
,cLastname VARCHAR(20) NOT NULL
,cPhone VARCHAR(20) NOT NULL
,cstreet VARCHAR(50)
,czipcode VARCHAR(5)
,CONSTRAINT customers_uk01 UNIQUE (
cFirstname
,cLastname
,cPhone
)
);
INSERT INTO customer (
cFirstname
,cLastname
,cPhone
,cstreet
,czipcode
)
VALUES (
'Dave'
,'Brown'
,'562-982-8696'
,'123 Lakewood Blvd. Long Beach'
,'90080'
)
,(
'Rachel'
,'Burris'
,'213-543-2211'
,'54 218th St. Torrance'
,'90210'
)
,(
'Tom'
,'Jewett'
,'714-555-1212'
,'10200 Slater'
,'92708'
)
,(
'Alvero'
,'Monge'
,'562-111-1234'
,'314159 Pi St. Long Beach'
,'90814'
),);
I'm getting the error at the line "insert into customer".
[Exception, Error code 30,000, SQLState 42X80] VALUES clause must
contain at least one element. Empty elements are not allowed.
What is causing the error?
Remove the extra ,) at the end of your query:
My requirement is that the column accno has no null value and no duplicates. The name column has no nulls and accepts only A to Z (no other like number or * $). The acctype columns is a character that allows only ( 'S' , 'C' ,'R') and the balance column has no null values. If acctype is S then balance should be >= 5000, when C the balance should be > 10000 and when it's R >= 5000.
I am trying to apply this with:
create table kcb_acc_tab
(accno varchar2(20)
constraint kcb_acc_Pk
primary key,
name varchar2(20)
constraint kcb_name_NN
Not null
constraint kcb_name_CK
check((name =upper(name)) and (name like '[(A-Z)]')),
Acctype char
constraint kcb_acctype_ck
check (acctype in('S' ,'C' ,'R')) ,
Doo timestamp
default sysdate ,
bal number(7,2) kcb_bal_NN
constraint kcb_bal_ck
check((aacctype ='S' and bal >=5000) or
(acctype = 'C' and bal >=10000) or
(acctype ='R' and bal >=5000));
This sounds like a perfect use-case for regular expressions, which I think is your intention with the like in your constraint.
I've considerably cleaned up your statement, you were missing a comma in the definition of kcb_bal_ck, and I've put the constraints at the end and added whitespace. This makes it easier, for me, to see what's going on and where any mistakes might be.
create table kcb_acc_tab(
accno varchar2(20) not null
, name varchar2(20) not null
, acctype char(1) not null -- missing size of column
, doo timestamp default sysdate not null -- missing not null
, bal number(7,2) not null
, constraint kcb_acc_pk primary key (accno)
, constraint kcb_name_ck check ( regexp_like(name, '[A-Z]', 'c' ) )
, constraint kcb_acctype_ck check ( acctype in ( 'S' ,'C' ,'R' ) )
-- acctype was spelled incorrectly.
, constraint kcb_bal_ck check( ( acctype ='S' and bal >= 5000 )
or ( acctype = 'C' and bal >= 10000 )
or ( acctype ='R' and bal >= 5000 )
) -- this parenthesis was missing
)
Here's a SQL Fiddle to demonstrate.
The main difference between this and your own is regexp_like(name, '[A-Z]', 'c' ). This ensures that the characters in the column name are solely contained within the group A-Z, that is the set of the upper-case Latin alphabet. The match_parameter 'c', specifies that the matching should be case-sensitive. The default case-sensitivity is determined by your NLS_SORT parameter, so you may not need to specify this explicitly but it's wise to do so.