Postgres update a diferent table - sql

Hello im trying to create a trigger, after insert on a certain column on a certain row the trgigger adds the that value on the other table on a certain place.
I have a table called updates:
create table public.updates (
id serial not null,
matricula varchar(10) NOT NULL,
primensalidade int,
segmensalidade int,
tercmensalidade int,
quamensalidade int,
quimensalidade int,
sexmensalidade int,
foreign key (id) references creditos(id));
And i have a table called:
CREATE TABLE public.creditos (
id serial NOT NULL,
veiculo varchar(10) NOT NULL,
matricula varchar(10) NOT NULL,
nome bpchar(30) NOT NULL,
telemovel varchar(10) NOT NULL,
valordevendapronto int4 NOT NULL,
juros int4 NULL,
valortotal int4 NULL,
entradainicial int4 NOT NULL,
primensalidade int4 NULL,
segmensalidade int4 NULL,
tercmensalidade int4 NULL,
quamensalidade int4 NULL,
quimensalidade int4 NULL,
sexmensalidade int4 NULL,
datainicial date NULL DEFAULT now(),
datafinal date NULL,
pago bpchar(3) NULL,
CONSTRAINT creditos_pkey PRIMARY KEY (id));
And my objective is after i insert on updates.primensalidade, it goes to creditos.primensalidade and change it to what i choosed before on updates.primensalidade where my creditos.matricula and updates.matricula are the same.
what i have soo far is:
CREATE OR REPLACE function creditoupdate()
RETURNS trigger
LANGUAGE plpgsql
AS $function$
begin
insert into creditos(primensalidade) values(new.primensalidade) where matricula = new.matricula ;
return new;
end;
$function$
;
create trigger creditoupdatetrigger after
insert
on
updates for each row execute function creditoupdate();
I hope you can help me thx.

WHERE cannot be used in INSERT like that.
To to update primensalidade column in table creditos, the following can be used:
UPDATE creditos SET primensalidade = new.primensalidade where matricula = new.matricula;
More about UPDATE - https://www.postgresql.org/docs/current/sql-update.html
More about INSERT - https://www.postgresql.org/docs/current/sql-insert.html

Related

Informix - Cant find syntax error

This may be a stupid mistake but I'm new to Informix and I can't seem to figure out why none of my CREATE TABLE statements won't run. I keep getting a syntax error on all of my CREATE TABLE statements.
CREATE TABLE customer(
store_num INTEGER NOT NULL,
store_name VARCHAR(20) NOT NULL,
addr VARCHAR(20),
addr2 VARCHAR(20),
city VARCHAR(15),
state VARCHAR(2),
zip-code VARCHAR(5),
contact_name VARCHAR(30),
phone VARCHAR(18),
CONSTRAINT cust_pk PRIMARY KEY(store_num)
);
create table orders(
order_num INTEGER NOT NULL,
order_date DATE NOT NULL,
store_num INTEGER NOT NULL,
fac_code CHAR(3),
ship_instr CHAR(10),
promo CHAR(1) NOT NULL,
CONSTRAINT orders_pk PRIMARY KEY(order_num)
);
create table factory(
fac_code CHAR(3) NOT NULL,
fac_name CHAR(15) NOT NULL,
CONSTRAINT fac_pk PRIMARY KEY(fac_code)
);
create table stock(
stock_num INTEGER NOT NULL,
fac_code CHAR(3) NOT NULL,
description CHAR(15) NOT NULL,
reg_price DECIMAL(8,2) NOT NULL,
promo_price DECIMAL(8,2),
price_updated DATE,
unit CHAR(4) NOT NULL,
CONSTRAINT stock_pk PRIMARY KEY(stock_num)
);
create table items(
order_num INTEGER NOT NULL,
stock_num INTEGER NOT NULL,
quantity SMALLINT NOT NULL,
price DECIMAL(8,2) NOT NULL,
CONSTRAINT items_pk PRIMARY KEY(order_num, stock_num)
);
create table state(
state_code CHAR(2) NOT NULL,
state_name CHAR(15) NOT NULL,
CONSTRAINT state_pk PRIMARY KEY(state_code)
);
Any help will be appreciated.
For reasons I don't understand, Informix requires the constraint name after the constraint, whereas standard SQL requires the constraint name before the constraint.
Thus, in addition to changing zip-code to zip_code (as pointed out by daniel.shih in an answer), you need:
CREATE TABLE customer(
store_num INTEGER NOT NULL,
store_name VARCHAR(20) NOT NULL,
addr VARCHAR(20),
addr2 VARCHAR(20),
city VARCHAR(15),
state VARCHAR(2),
zip_code VARCHAR(5),
contact_name VARCHAR(30),
phone VARCHAR(18),
PRIMARY KEY(store_num) CONSTRAINT cust_pk
);
You can try customer's field zip_code instead of zip-code

i am trying to create tables but it show me 2 errors, how i fix it?

2 errors were found during analysis.
Unexpected beginning of statement. (near "admin_id" at position 349)
Unrecognized statement type. (near "INT" at position 358)
CREATE TABLE Users (
user_id INT NOT NULL AUTO_INCREMENT,
email VARCHAR(80) NOT NULL,
password CHAR(41) NOT NULL,
name VARCHAR(50) NOT NULL,
phone VARCHAR(20) NOT NULL,
gender VARCHAR(6) NOT NULL,
fbinfo VARCHAR(50) NOT NULL,
age INT NOT NULL,
PRIMARY KEY (user_id),
UNIQUE INDEX (email)
)
CREATE TABLE Admin (
admin_id INT NOT NULL AUTO_INCREMENT,
email VARCHAR(80) NOT NULL,
password CHAR(41) NOT NULL,
PRIMARY KEY (admin_id),
UNIQUE INDEX (email)
)
CREATE TABLE Task (
task_id INT NOT NULL AUTO_INCREMENT,
tex VARCHAR(140) NOT NULL,
datetime DATE,
status INT,
calendar BOOLEAN,
PRIMARY KEY (task_id),
lat DECIMAL(9,6),
long DECIMAL(9,6)
)
If you are doing this in one execution, you would need to include a ; at the end of each of your table creation statements.
CREATE TABLE Users (
user_id INT NOT NULL AUTO_INCREMENT,
email VARCHAR(80) NOT NULL,
password CHAR(41) NOT NULL,
name VARCHAR(50) NOT NULL,
phone VARCHAR(20) NOT NULL,
gender VARCHAR(6) NOT NULL,
fbinfo VARCHAR(50) NOT NULL,
age INT NOT NULL,
PRIMARY KEY (user_id),
UNIQUE INDEX (email)
);
CREATE TABLE Admin (
admin_id INT NOT NULL AUTO_INCREMENT,
email VARCHAR(80) NOT NULL,
password CHAR(41) NOT NULL,
PRIMARY KEY (admin_id),
UNIQUE INDEX (email)
);
CREATE TABLE Task (
task_id INT NOT NULL AUTO_INCREMENT,
tex VARCHAR(140) NOT NULL,
datetime DATE,
status INT,
calendar BOOLEAN,
PRIMARY KEY (task_id),
lat DECIMAL(9,6),
long DECIMAL(9,6)
);

Error converting data type varchar to numeric while inserting data

I have a problem with my first insert statement. I have searched online and nothing seems to help my understanding of this problem or how to fix it. When I execute the insert statement it gives me the message:
Error converting data type varchar to numeric.
Table structure:
CREATE TABLE BOOKS
(
ISBN INT NOT NULL UNIQUE,
TITLE VARCHAR(25) NOT NULL,
AuthorFname VARCHAR(20) NOT NULL,
AuthorLname VARCHAR(20) NOT NULL,
GENRE VARCHAR(10) NOT NULL,
PUBLISHER VARCHAR(30) NOT NULL,
PUBLISHERDATE DATE NOT NULL,
DESCRIPTION VARCHAR(300) NOT NULL,
EDITION varchar(100) NOT NULL,
FORMAT VARCHAR(20) NOT NULL,
PAGENUMBER INTEGER NOT NULL,
FILESIZE TEXT NOT NULL,
IMAGE varchar(20) NOT NULL,
THUMBNAIL varchar(20) NOT NULL,
PRICE DECIMAL(9,2) NOT NULL,
AVAILABILITY VARCHAR(20) NOT NULL,
PRIMARY KEY(ISBN),
FOREIGN KEY(TITLE) REFERENCES WISHLIST(TITLE)
)
CREATE TABLE USERINFORMATION
(
USEREMAIL VARCHAR(30) NOT NULL UNIQUE,
USERNAME VARCHAR(30) NOT NULL,
PASSWORD TEXT NOT NULL,
QUESTION1 TEXT NOT NULL,
QUESTION2 TEXT NOT NULL,
ANSWER1 VARCHAR(25) NOT NULL,
ANSWER2 VARCHAR(25) NOT NULL,
BIRTHDATE DATE NOT NULL,
TITLE VARCHAR(25) NOT NULL,
PRIMARY KEY(USEREMAIL),
FOREIGN KEY(USERNAME) REFERENCES REVIEWS(USERNAME)
)
CREATE TABLE BILLINGINFO
(
FIRSTNAME VARCHAR(20) NOT NULL UNIQUE,
LASTNAME VARCHAR(20) NOT NULL,
USERNAME VARCHAR(20) NOT NULL,
ADDRESS1 VARCHAR(35) NOT NULL,
ADDRESS2 VARCHAR(35) NOT NULL,
CITY VARCHAR(25) NOT NULL,
STATE VARCHAR(35) NOT NULL,
ZIP INTEGER NOT NULL,
PHONE INTEGER NOT NULL,
PAYMENTTYPE TEXT NOT NULL,
CARDNUMBER INTEGER NOT NULL,
SECURITYCODE INTEGER NOT NULL,
EXPIRATIONDATE DATE NOT NULL,
PRIMARY KEY(FIRSTNAME)
)
CREATE TABLE LENDINGHISTORY
(
TITLE VARCHAR(25) NOT NULL UNIQUE,
CHECKUOTDATE DATE NOT NULL,
DUEDATE DATE NOT NULL,
STATUS TEXT NOT NULL,
USERNAME VARCHAR(20) NOT NULL,
RETURNEDDATE DATE NOT NULL,
PRIMARY KEY(TITLE)
)
CREATE TABLE WISHLIST
(
TITLE VARCHAR(25) NOT NULL UNIQUE,
AUTHORFNAME TEXT NOT NULL,
AUTHORLNAME TEXT NOT NULL,
THUMBNAIL VARCHAR(20) NOT NULL,
GENRE VARCHAR(10) NOT NULL,
PRICE DECIMAL(9,2) NOT NULL,
PRIMARY KEY(TITLE)
)
CREATE TABLE REVIEWS
(
USERNAME VARCHAR(30) NOT NULL UNIQUE,
REVIEWTEXT VARCHAR(40) NOT NULL,
RATING INT NOT NULL,
TITLE VARCHAR(25) NOT NULL,
PRIMARY KEY(USERNAME)
)
ALTER TABLE REVIEWS
ADD FOREIGN KEY(TITLE)
REFERENCES WISHLIST(TITLE)
INSERT INTO BOOKS
VALUES ('0547928220', 'The Hobbit', 'J.J.R.', 'Tolkien', 'Fantasy', 'Houghton Mifflin Harcourt', '9-18-2012',
'"In a hole in the ground, there lived a hobbit." So begins one of the most beloved and delightful tales in the English language. Set in the imaginary world of Middle-earth, at once a classic myth and a modern fairy tale, The Hobbit is one of literature s most enduring and well-loved novels.',
'75Th Anniversary Edition', 'PaperBack', '320', 'N/A', 'the_Hobbit', 'the_Hobbit2', '$8.30', 'Available');
SELECT *
FROM BOOKS
I think there are a few different things going on here. First of all, you have a line that reads drop TABLE BOOKS before the insert, which will remove the table from the registry before you can add any rows to it.
Secondly, the numerics you're trying to insert are surrounded by quotes and SQL doesn't do very well with implicit conversions to begin with. Your ISBN should probably be a VARCHAR since it contains a leading 0, which will be dropped in the event it actually converts. So #marc_s is right, drop the quotes from all your numeric values to be inserted; this includes ISBN (currently), page number, and price.
I believe the error actually refers to what you have entered in the price field, which is $8.30. A numeric doesn't know how to read $ in SQL. Also, there is a data type that coners such needs called money. Drop the $ and change the data type of the price column to money and you should be OK.
Hope this helps.
-C§

Microsoft SQL, foreign key not referencing table, can't see what's causing it

I've spent a while trying to firgure it but but I can't see anything that would be causing this error. I'm thinking maybe something to do with the "Unique" statement.
Msg 1767, Level 16, State 0, Line 40
Foreign key 'FK_Loan_ItemNo__0AD2A005' references invalid table
'Item'.
Here's the code if someone wants to use it to replicate problem:
CREATE DATABASE LibrarySystem10
GO
USE LibrarySystem10
GO
CREATE TABLE MemberType(
MemberTypeNo int NOT NULL,
Name varchar(50) NOT NULL,
Description varchar(250) NOT NULL,
MaxNumberLoans int NOT NULL,
MaxLoanDuration int NOT NULL
PRIMARY KEY (MemberTypeNo)
)
insert into MemberType values ('0','UnderGraduate','A student at a college or university who has not yet earned a bachelor''s or equivalent degree.','5','10')
insert into MemberType values ('1','PostGraduate','A student undertaking study after completing a first degree.','10','10')
insert into MemberType values ('2','Staff','Staff at the university','15','15')
CREATE TABLE Member(
MemberNo int NOT NULL,
MemberTypeNo int NOT NULL,
FirstName varchar(150) NOT NULL,
LastName varchar(150) NULL,
DateOfBirth varchar (200) NULL,
HouseNo int NOT NULL,
Street varchar(50) NOT NULL,
Suburb varchar(100) NOT NULL,
PostCode int NOT NULL,
EmailAddress varchar(250) NULL,
HomePhoneNo varchar(250) NULL,
MobileNo varchar(250) NULL,
MembershipStartDate varchar (200) NOT NULL,
MembershipEndDate varchar (200) NOT NULL,
MembershipStatus varchar(100) NOT NULL,
PinNo int NOT NULL
PRIMARY KEY (MemberNo)
FOREIGN KEY (MemberTypeNo)REFERENCES MemberType ON UPDATE CASCADE
)
insert into member values ('0','0','Shane','Lindsay','15-11-1992','90','fake st','FauxTon','2250','shane#hotmai.com','0243296356','0415657164','15-11-2010','15-11-2020','current','0105')
insert into member values ('1','0','Shaune','Lincoln','18-12-1992','92','faken st','FauxTone','2350','shaune27#hotmai.com','0243253357','041565757','14-12-2010','14-12-2020','deferred','0123')
insert into member values ('2','0','Sarah','richards','08-08-1990','45','Small st','Hornsby','2279','Sarah67#hotmai.com','02432567154','0416451845','01-01-2012','01-01-2022','current','0123')
CREATE TABLE Loan(
MemberNo int NOT NULL FOREIGN KEY(MemberNo) REFERENCES Member ON UPDATE CASCADE,
ItemNo int NOT NULL FOREIGN KEY(ItemNo) REFERENCES Item ON UPDATE CASCADE,
DateLoaned varchar (50) NOT NULL,
DueDate varchar (50) NOT NULL,
Status varchar(50) NOT NULL,
FinesImposed bit NOT NULL DEFAULT '0' CHECK (finesImposed IN ('0','1')) ,
Renewed bit NOT NULL DEFAULT '0' CHECK (Renewed IN ('0','1')),
UNIQUE(MemberNo,ItemNo,DateLoaned)
)
insert into Loan values ('0','0','10-10-2012','15-10-2012','loaned','0','0')
insert into Loan values ('1','0','12-10-2012','15-10-2012','loaned','0','1')
CREATE TABLE Item(
ItemNo int NOT NULL,
Title varchar(50) NOT NULL,
Subject varchar(100) NULL,
ISBN int NULL,
PhysicalDescription varchar(150) NULL,
Author varchar(75) NULL,
PRIMARY KEY (ItemNo)
)
insert into Item values ('0','Book1','IT','0501425252','Big,42pages','John Doe')
insert into Item values ('1','Book2','IT','0501425253','Big,42pages','John Doe')
CREATE TABLE ItemCopy(
ItemNo int NOT NULL,
CallNumber varchar(50) NOT NULL,
Condition varchar(50) NULL,
UNIQUE(ItemNo,CallNumber),
PRIMARY KEY (CallNumber)
)
insert into ItemCopy values ('0','0','good')
CREATE TABLE Hold(
HoldNo int NOT NULL,
MemberNo int NOT NULL FOREIGN KEY(MemberNo) REFERENCES Member ON UPDATE CASCADE,
ItemNo int NOT NULL FOREIGN KEY(ItemNo) REFERENCES Item ON UPDATE CASCADE,
DateTimeHeld datetime NOT NULL,
comments varchar(200) NULL,
Status varchar(50) NOT NULL
PRIMARY KEY (HoldNo)
)
CREATE TABLE Fine(
FineNo int NOT NULL,
MemberNo int NOT NULL FOREIGN KEY(MemberNo) REFERENCES Member ON UPDATE CASCADE,
Description varchar(50) NULL,
Amount int NOT NULL,
PRIMARY KEY (FineNo)
)
CREATE TABLE AudioRecording(
Length varchar(50) NULL,
BitRate varchar(50) NULL,
Size varchar(50) NULL
)
CREATE TABLE ItemCollection(
ItemNo int NULL,
CollectionName varchar(75) NULL
UNIQUE (ItemNo,CollectionName)
)
CREATE TABLE Collection(
CollectionName varchar(75)NOT NULL
PRIMARY KEY (CollectionName)
)
CREATE TABLE Book(
PublisherInfo varchar(150) NULL,
Edition int NULL,
Notes varchar(250) NULL,
Status varchar(50) NULL
)
CREATE TABLE Journal(
Series int NULL,
Notes varchar(250) NULL,
OtherTitles varchar(150) NULL,
PriorTitles varchar(250) NULL
)
SELECT m.FirstName, l.Status, l.DueDate
FROM Member m, Loan l
WHERE m.MemberNo = '0' AND l.MemberNo = m.MemberNo
Loan references Item, but you create Loan before you create Item. Create the Item table first.

trigger in sql problem

this is my trigger
ALTER trigger [dbo].[addpay]
on [dbo].[pays]
after insert
as
declare #idtutor int
set #idtutor =(select idtutor from inserted)
begin
insert into pays (idtutor,nopay,datex,paythismonth)values (#idtutor,600,GETDATE(),'no')
end
but it doesn't add a new pays after inserted a tutor... i dont watch any bug, mistake, why doesn't it work
my tables
create table Tutor
(
[IdTutor] int primary key identity not null,
[Nombre] varchar(150) not null,
[ApellidoPaterno] varchar (150) not null,
[ApellidoMaterno] varchar (150) not null,
[EstadoCivil] varchar (10) not null,
[FechaNacimiento] varchar(50),
[Municipio] varchar(150) not null,
[Estado] varchar(150) not null,
[Direccion] varchar(250) not null,
[Sexo] varchar (9) not null,
[TelefonoTutor] char(10) not null,
[CelularTutor] char(15) not null,
[EmailTutor] char(50) not null,
[Empresa] varchar(150) not null,
[Ocupacion] varchar(250) not null,
[DireccionEmpresa] varchar (250) not null,
[TelefonoEmpresa] char(10) not null,
[CelularEmpresa] char(15) not null,
[EmailEmpresa] varchar(50) not null
)
create table pays
(
idpay int primary key not null identity,
idtutor int not null,
nopay float,
datex datetime,
paythismonth varchar(2)
)
You need to create the trigger on the table for where you want it to fire when a new record is inserted (Tutor in this case).
Additionally you need to remember that inserts/update statements can affect multiple rows so assigning to scalar variables won't work. The trigger you need is
CREATE TRIGGER YourTrigger
ON [dbo].[Tutor]
AFTER INSERT
AS
BEGIN
SET NOCOUNT ON
INSERT INTO pays
(idtutor,
nopay,
datex,
paythismonth)
SELECT idtutor,
600,
GETDATE(),
'no'
FROM inserted
END
You will also need to drop the other trigger in your question with DROP TRIGGER [dbo].[addpay]