Open Office Base: How to Create a INSERT Trigger - sql

I am creating a database using OpenOffice Base and some homebrewed sql. Problems come in when trying to reference a foreign key that is numbers and possibly letters. I would like to force the table I am checking the key on to force the inserts to uppercase (or lower, I am not picky) and do the same to the table that is doing the checking. The tables:
DROP TABLE IF EXISTS Gun;
DROP TABLE IF EXISTS Model;
DROP TABLE IF EXISTS Value;
CREATE TABLE Model (
"Model Name" VARCHAR (25) NOT NULL PRIMARY KEY,
"Manufacuture" VARCHAR (15) NOT NULL,
"Manufactured Start Year" INTEGER NOT NULL,
"Manufactured End Year" INTEGER,
"Gun Type" VARCHAR (10),
"Value Mininum" DECIMAL (10, 2),
"Value Maximum" DECIMAL (10, 2) NOT NULL,
"Description" VARCHAR (500)
);
CREATE TABLE Gun (
"Serial Number" VARCHAR (25) NOT NULL,
"Model Name" VARCHAR (25),
"Caliber" VARCHAR (10),
"Unique Features" VARCHAR (200),
"Manufactured Date" INTEGER,
"Condition" INTEGER,
CONSTRAINT FK_MODEL FOREIGN KEY ("Model Name") REFERENCES Model ("Model Name"),
CONSTRAINT PK_GUN_KEY PRIMARY KEY ("Serial Number", "Model Name"),
CONSTRAINT CK_CONDITION CHECK( "Condition" <= 100 )
);
The Trigger (that doesn't work and is one of many I have tried):
CREATE TRIGGER ForceUpper BEFORE INSERT ON Model
SET Model."Model Name" = UPPER(Model."Model Name");
Which gives:
Unexpected end of command: SET in statement
Any tips on what I am doing wrong would be nice. The HyperSQL docs I looked at were of little help besides adding BEGIN ATOMIC which also had unexpected end of command (even with END). Thanks

Checking HSQLDB documentation, I think your syntax should be:
create trigger ForceUpper before insert on Model
for each row set new."Model Name" = UPPER(new."Model Name")
That new keyword refers to the new row that is being inserted
Note: I suggest you avoid using spaces in table and/or column names. If you need to separate words, either use _ instead of spaces or use CamelCase.

Related

changing the name of a column in postgresql database

I'm trying to modify the name a column named "photo_url". I tried to simply changing the string name to "test" and killing the postgresql service and then re starting it again, but it doesn't seem to be working; it still loads up as "photo_url".
I'm not sure how to change the name if anyone could help me it would be greatly appreciated.
this is my table im using postgreSQL, and pgweb to view my database, i used dbdesigner to generate this schema
CREATE TABLE "users" (
"user_id" serial NOT NULL,
"name" TEXT NOT NULL,
"instrument" TEXT NOT NULL,
"country" TEXT NOT NULL,
"state" TEXT NOT NULL,
"city" TEXT NOT NULL,
"about" TEXT NOT NULL,
"email" TEXT NOT NULL UNIQUE,
"hashed_password" TEXT NOT NULL,
"photo_url" TEXT NOT NULL,
"created_at" timestamptz NOT NULL default now(),
CONSTRAINT "users_pk" PRIMARY KEY ("user_id")
) WITH (
OIDS=FALSE
);
If you've already created the table, you can use this query to rename the column
ALTER TABLE users RENAME COLUMN photo_url TO test;
otherwise simply recreate your table with the new column name.
More information on the ALTER TABLE command can be found in the PostgreSQL Docs.

Constraint not working as desired for my INSERT?

I am creating a Table named "Cliente" with some constraints on it as it follows:
CREATE TABLE public."Cliente" (
"K_CODCLIENTE" numeric(5) NOT NULL,
"N_NOMBRE1" varchar(15) NOT NULL,
"N_NOMBRE2" varchar(15) NOT NULL,
"N_APELLIDO1" varchar(15) NOT NULL,
"N_APELLIDO2" varchar(15),
"N_DIRECCION" varchar(50) NOT NULL,
"Q_TELEFONO" numeric(10) NOT NULL,
"K_CODREF" numeric(5),
"I_TIPOID" varchar(2) NOT NULL,
"Q_IDENTIFICACION" varchar(10) NOT NULL,
CONSTRAINT "PK_Cliente" PRIMARY KEY ("K_CODCLIENTE"),
CONSTRAINT "UQ_ID_TIPOID_CLIENTE" UNIQUE ("I_TIPOID","Q_IDENTIFICACION"),
CONSTRAINT "CK_CODCLIENTE" CHECK ("K_CODCLIENTE" >= 100),
CONSTRAINT "CK_Q_IDENTIFICACION" CHECK ("Q_IDENTIFICACION" IN ('CC', 'PA', 'CE', 'NI', 'OT'))
);
When I try to insert some values on it:
INSERT INTO "Cliente"
VALUES ('101','Juan','Felipe','Ortiz','Rojas','AK 15 no. 28-05','3101125507',null,'CC','51111111');
I get the following error (in PostgreSQL 14, on Fedora):
[23514] ERROR: new row for relation "Cliente" violates check constraint "CK_Q_IDENTIFICACION"
Detail: Failing row contains (101, Juan, Felipe, Ortiz, Rojas, AK 15 no. 28-05, 3101125507, null, CC, 51111111).
I am trying to restrict the "Q_IDENTIFICACION" column so it can only be filled with 'CC', 'PA', 'CE, 'NI' or 'OT'.
Maybe I'm doing something wrong when declaring the constraint "CK_Q_IDENTIFICACION"?
Seems like you messed up the mapping of values and are trying to insert '51111111' to "Q_IDENTIFICACION".
Consider this more revealing variant with a formatted list of target columns:
INSERT INTO "Cliente"
("K_CODCLIENTE", "N_NOMBRE1", "N_NOMBRE2", "N_APELLIDO1", "N_APELLIDO2", "N_DIRECCION" , "Q_TELEFONO", "K_CODREF", "I_TIPOID", "Q_IDENTIFICACION")
VALUES ('101' , 'Juan' ,'Felipe' , 'Ortiz' , 'Rojas' , 'AK 15 no. 28-05', '3101125507', NULL , 'CC' , '51111111'); -- !
Maybe you want to switch the last two column names in the table definition - and (not) adapt the VALUES list in the INSERT accordingly? (varchar(2) vs. varchar(10) seems switched as well.)
For persisted code, it's generally advisable to spell out target columns in an INSERT command in any case.
Asides:
Reconsider all these pesky double-quoted upper case identifiers. See:
Are PostgreSQL column names case-sensitive?
Consider plain type text instead of varchar(n) with strikingly tight character limits. See:
Any downsides of using data type "text" for storing strings?

CHECK with ^[A-Z]{3}[0-9]{6}$ - SQL Server

CREATE TABLE PARTICIPANTE(
pasaporte NVARCHAR(9) NOT NULL,
nombre NVARCHAR(50) NOT NULL,
sexo CHAR(1) NOT NULL,
fecNac DATE NOT NULL,
codPais NVARCHAR(3) NOT NULL,
CONSTRAINT PK_PARTICIPANTE PRIMARY KEY (pasaporte),
CONSTRAINT FK_PAIS_PARTICIPANTE FOREIGN KEY (codPais) REFERENCES PAIS(codigo),
CONSTRAINT CHK_PASAPORTE CHECK (pasaporte like '^\[A-Z\]{3}\[0-9\]{6}$')
)
The CONSTRAINT CHK_PASAPORTE doesn't work when I try to insert the data.
The INSERT statement conflicted with the CHECK constraint "CHK_PASAPORTE". The conflict occurred in database "OMA", table "dbo.PARTICIPANTE", column 'pasaporte'.
Example
insert into PARTICIPANTE (pasaporte,nombre,sexo,fecNac,codPais) value ('JPN865653','Noguchi','F','20000104','JPN');
Can someone explain to me why this doesn't work and how can I fix it?
As I mention in the comments, SQL Server has no (in built) support for Regex, it only has basic pattern matching, which is explained in the documentation.
Fortunately, the logic you are after appears to be quite simple; 3 letters followed by 6 digits. This can be achieved with the following constraint:
ALTER TABLE dbo.PARTICIPANTE ADD CONSTRAINT CHK_PASAPORTE CHECK (pasaporte LIKE '[A-Z][A-Z][A-Z][0-9][0-9][0-9][0-9][0-9][0-9]');
Note that if you require the value to only contain uppercase values, you'll need to COLLATE the value to a collation that is case sensitive and orders upper case letters first, then lowercase, and finally alphabetically (Binary collations are one such one that does this).

SQL: Check constraints syntax errors?

I'm trying to add a constraint to one of my columns, however i get this error message "missing right parenthesis". Not the first time I get this message, however I'm fairly new to SQL, so my syntax is not on par.
CREATE TABLE FAGFELT
(
bok varchar (255) PRIMARY KEY,
felt varchar (255)
CREATE CONSTRAINT chk_felt CHECK (felt IN("databaser", "programmering", "matematikk", "statistikk", "kjemi", "fysikk"))
);
The create constraint is wrong, and string constants need to be supplied in single quotes '. Double quotes " are for identifiers
CREATE TABLE FAGFELT
(
bok varchar (255) PRIMARY KEY,
felt varchar (255), --<< you need a comma here
CONSTRAINT chk_felt
CHECK (felt IN('databaser', 'programmering', 'matematikk', 'statistikk', 'kjemi', 'fysikk'))
);

Insert fails due to "column not allowed here" error

I am a beginner with SQL. I have created 4 tables and added data to my SHIP table. I am having some issues with inserting data into the CRUISE table. I get the error message at the bottom.
I have researched and can not figure out what i am doing wrong. Is there an issue with my sequence and/or trigger that is not allowing me to do this or is my syntax in the CREATE TABLE CRUISE causing the error? Everything i have done has been successful up until trying to insert the first column into the CRUISE table.
The tables:
CREATE TABLE SHIP
( Ship_Name VARCHAR2(100) PRIMARY KEY,
Ship_Size INTEGER,
Ship_Registry VARCHAR2(50),
Ship_ServEntryDate INTEGER,
Ship_PassCapacity INTEGER,
Ship_CrewCapacity INTEGER,
Ship_Lifestyle VARCHAR2(40),
CONSTRAINT Size_ck CHECK (Ship_Size > 0),
CONSTRAINT Registry_ck CHECK (Ship_Registry IN ('Norway','Liberia','The Netherlands','Bahamas'))
)
CREATE TABLE CRUISE (
Cruise_ID INTEGER Primary Key,
Ship_Name VARCHAR(100),
Cruise_DeptDate DATE NOT NULL,
Cruise_DeptCity VARCHAR(80) NOT NULL,
Cruise_Duration INTEGER,
FOREIGN KEY (Ship_Name) REFERENCES SHIP(Ship_Name)
)
CREATE TABLE PASSENGERS (
Pass_ID INTEGER PRIMARY KEY,
Pass_Name VARCHAR(100) NOT NULL,
Pass_City VARCHAR(80),
Pass_Telephone VARCHAR(15),
Pass_NextOfKin VARCHAR(100)
)
CREATE TABLE RESERVATIONS (
Pass_ID INTEGER NOT NULL,
Cruise_ID INTEGER NOT NULL,
Res_TotalCost NUMERIC(9,2),
Res_BalanceDue NUMERIC(9,2),
Res_SpecialRequest VARCHAR(30),
Res_Room VARCHAR(10),
FOREIGN KEY (Pass_ID) REFERENCES PASSENGERS(Pass_ID),
FOREIGN KEY (Cruise_ID) REFERENCES CRUISE(Cruise_ID),
CONSTRAINT Cost_ck CHECK (Res_TotalCost >= 0),
CONSTRAINT BalanceDue_ck CHECK (Res_BalanceDue >= 0),
CONSTRAINT SpecialRequest_ck CHECK (Res_SpecialRequest IN ('Vegetarian','Vegan','Low salt','Gluten free','Kosher','Other'))
)
The sequence/trigger is an attempt to auto number Cruise_ID.
Create SEQUENCE cruise_id_sq
START WITH 1
INCREMENT BY 1;
CREATE OR REPLACE TRIGGER cruise_id_t
BEFORE INSERT
ON CRUISE
REFERENCING NEW AS NEW
FOR EACH ROW
BEGIN
if(:new.Cruise_ID is null) then
SELECT cruise_id_sq.nextval
INTO :new.Cruise_ID
FROM dual;
end if;
END;
ALTER TRIGGER cruise_id_t ENABLE;
Inserting into SHIP is okay....
INSERT INTO SHIP
(Ship_Name, Ship_Size, Ship_Registry,Ship_ServEntryDate, Ship_PassCapacity,Ship_CrewCapacity,Ship_Lifestyle)
Values ('Carribean Princess',142000,'Liberia',1000,3100,1181,'Contemporary');
INSERT INTO SHIP
(Ship_Name, Ship_Size, Ship_Registry,Ship_ServEntryDate, Ship_PassCapacity,Ship_CrewCapacity,Ship_Lifestyle)
Values ('Carribean Sunshine',74000,'Norway',1992,1950,760,'Premium');
INSERT INTO SHIP
(Ship_Name, Ship_Size, Ship_Registry,Ship_ServEntryDate, Ship_PassCapacity,Ship_CrewCapacity,Ship_Lifestyle)
Values ('Ship of Dreams',70000,'Liberia',2004,1804,735,'Contemporary');
INSERT INTO SHIP
(Ship_Name, Ship_Size, Ship_Registry,Ship_ServEntryDate, Ship_PassCapacity,Ship_CrewCapacity,Ship_Lifestyle)
Values ('Sunshine of the Seas',74000,'The Netherlands',1990,2354,822,'Luxury');
Inserting into CRUISE fails...
INSERT INTO Cruise
(Ship_Name, Cruise_DeptDate,Cruise_DeptCity,CruiseDuration)
Values ('Sunshine of the Seas',25-may-15,'Miami',10);
Error starting at line : 1 in command - INSERT INTO Cruise (Ship_Name,
Cruise_DeptDate,Cruise_DeptCity,CruiseDuration) Values ('Sunshine of
the Seas',25-may-15,'Miami',10) Error at Command Line : 3 Column : 35
Error report - SQL Error: ORA-00984: column not allowed here
00984. 00000 - "column not allowed here"
*Cause:
*Action:
Oracle thinks that 25-may-15 is the expression 25 minus may minus 15. In looking up the value for may Oracle finds that there is nothing there. Thus the error.
You can, but probably don't want to, quote it like so, '25-may-15'. This will make a string that may or may not be implicitly converted to a date, depending on the settings of NLS_DATE_FORMAT and or NLS_TERRITORY.
To form a date independent of session setting one can use the TO_DATE function with explicit date format, to_date('25-may-15', 'DD-Mon-YY'). Another option is a date literal, date '2015-05-25', which is always YYYY-MM-DD no matter the session settings..