Error "Token unknown - line 4, column 2; SET" creating trigger with variables - sql

I want to create a trigger, but I'm getting an error.
I have 2 tables STOK and STOK_HAREKET:
STOK = (ID,URUN,FIYAT,MINIMUM,MAXIMUM)\
STOK_HAREKET = (STOK_ID,FİYAT,GIRIS,CIKIS)\
I want to build a trigger to STOK_HAREKET. On insert and update, the GIRIS and CIKIS ın STOK_HAREKET table is collected and submitted
from the output and save this value to the MAXIMUM value ın the STOK table.
CREATE TRIGGER T_STOK_BIU FOR STOK_HAREKET BEFORE INSERT OR UPDATE
AS
begin
Set #gsum = ( SELECT SUM(GIRIS) FROM STOK_HAREKET WHERE STOK_ID = new.STOK_ID );
Set #csum = ( SELECT SUM(CIKIS) FROM STOK_HAREKET WHERE STOK_ID = new.STOK_ID );
Set #toplm = (#gsum-#csum)
update STOK set MAKSIMUM = #toplm where ID = new.STOK_ID
end
This code gives an error:
org.jkiss.dbeaver.model.sql.DBSQLException: SQL Error [335544634] [42000]: Dynamic SQL Error; SQL error code = -104; Token unknown - line 4, column 2; SET [SQLState:42000, ISC error code:335544634]
at org.jkiss.dbeaver.model.impl.jdbc.exec.JDBCStatementImpl.executeStatement(JDBCStatementImpl.java:133)
at org.jkiss.dbeaver.ui.editors.sql.execute.SQLQueryJob.executeStatement(SQLQueryJob.java:578)
at org.jkiss.dbeaver.ui.editors.sql.execute.SQLQueryJob.lambda$1(SQLQueryJob.java:487)
at org.jkiss.dbeaver.model.exec.DBExecUtils.tryExecuteRecover(DBExecUtils.java:173)
at org.jkiss.dbeaver.ui.editors.sql.execute.SQLQueryJob.executeSingleQuery(SQLQueryJob.java:494)
at org.jkiss.dbeaver.ui.editors.sql.execute.SQLQueryJob.extractData(SQLQueryJob.java:913)
at org.jkiss.dbeaver.ui.editors.sql.SQLEditor$QueryResultsContainer.readData(SQLEditor.java:3760)
at org.jkiss.dbeaver.ui.controls.resultset.ResultSetJobDataRead.lambda$0(ResultSetJobDataRead.java:123)
at org.jkiss.dbeaver.model.exec.DBExecUtils.tryExecuteRecover(DBExecUtils.java:173)
at org.jkiss.dbeaver.ui.controls.resultset.ResultSetJobDataRead.run(ResultSetJobDataRead.java:121)
at org.jkiss.dbeaver.ui.controls.resultset.ResultSetViewer$ResultSetDataPumpJob.run(ResultSetViewer.java:5033)
at org.jkiss.dbeaver.model.runtime.AbstractJob.run(AbstractJob.java:105)
at org.eclipse.core.internal.jobs.Worker.run(Worker.java:63)
Caused by: java.sql.SQLSyntaxErrorException: Dynamic SQL Error; SQL error code = -104; Token unknown - line 4, column 2; SET [SQLState:42000, ISC error code:335544634]
at org.firebirdsql.gds.ng.FbExceptionBuilder$Type$1.createSQLException(FbExceptionBuilder.java:534)
at org.firebirdsql.gds.ng.FbExceptionBuilder.toFlatSQLException(FbExceptionBuilder.java:304)
at org.firebirdsql.gds.ng.wire.AbstractWireOperations.readStatusVector(AbstractWireOperations.java:140)
at org.firebirdsql.gds.ng.wire.AbstractWireOperations.processOperation(AbstractWireOperations.java:204)
at org.firebirdsql.gds.ng.wire.AbstractWireOperations.readSingleResponse(AbstractWireOperations.java:171)
at org.firebirdsql.gds.ng.wire.AbstractWireOperations.readResponse(AbstractWireOperations.java:155)
at org.firebirdsql.gds.ng.wire.AbstractWireOperations.readGenericResponse(AbstractWireOperations.java:257)
at org.firebirdsql.gds.ng.wire.AbstractFbWireDatabase.readGenericResponse(AbstractFbWireDatabase.java:201)
at org.firebirdsql.gds.ng.wire.version11.V11Statement.prepare(V11Statement.java:89)
at org.firebirdsql.jdbc.FBStatement.prepareFixedStatement(FBStatement.java:881)
at org.firebirdsql.jdbc.FBStatement.internalExecute(FBStatement.java:868)
at org.firebirdsql.jdbc.FBStatement.executeImpl(FBStatement.java:496)
at org.firebirdsql.jdbc.FBStatement.execute(FBStatement.java:482)
at org.jkiss.dbeaver.model.impl.jdbc.exec.JDBCStatementImpl.execute(JDBCStatementImpl.java:329)
at org.jkiss.dbeaver.model.impl.jdbc.exec.JDBCStatementImpl.lambda$0(JDBCStatementImpl.java:131)
at org.jkiss.dbeaver.utils.SecurityManagerUtils.wrapDriverActions(SecurityManagerUtils.java:96)
at org.jkiss.dbeaver.model.impl.jdbc.exec.JDBCStatementImpl.executeStatement(JDBCStatementImpl.java:131)
... 12 more
Caused by: org.firebirdsql.jdbc.FBSQLExceptionInfo: Dynamic SQL Error

The syntax you use is not valid syntax for Firebird. I recommend you review the Firebird 4.0 Language Reference, chapter Procedural SQL (PSQL) Statements for the correct syntax for Firebird.
Specifically, you need to explicitly declare variables before use, and use select ... into ... to assign values from a select.
However, there are more problems with your trigger:
You execute two separate selects, which could have been one select
You retrieve values using two selects, and then use those for an update. This can be done in one merge statement
As user13964273 remarks in the comments, doing this is a bad idea because of transaction visibility and performance (or having to retry concurrent updates which conflict)
Taken at face value, your trigger could be rewritten to:
create trigger T_STOK_BIU for STOK_HAREKET before insert or update
as
begin
merge into STOK
using (
select STOK_ID, sum(GIRIS) - sum(CIKIS) as toplm
from STOK_HAREKET
where STOK_ID = new.STOK_ID
group by STOK_ID
) as src
on STOK.STOK_ID = src.STOK_ID
when matched then update set STOK.MAKSIMUM = src.toplm;
end
However, you should consider instead using a view to calculate this on the fly when needed. Or use a table which has a summarized aggregate row, and insert changes (delta rows) into the table through a trigger, and on a schedule recompute the summarized aggregate row and delete those delta rows. You can then - use a view to calculate the actual value when needed, while reducing performance concurrency issues.

Related

structured query language error when running the code

When I try to run the below code; I received the following error.
CREATE PROCEDURE proc_test
(IN roger_value INT, dd VARCHAR(100), way_id INT)
LANGUAGE SQL MODIFIES SQL DATA
INSERT INTO testall
VALUES
(000, roger_value, dd, 777, way_id);
CREATE TRIGGER test1
AFTER INSERT ON testall
FOR EACH ROW mode DB2SQL
UPDATE testall
SET way_out = way_out + 1,
way_in = way_in + 1;
CREATE TRIGGER test2
AFTER INSERT ON testall
FOR EACH ROW mode DB2SQL
DELETE FROM testfirst
WHERE (SELECT testfirst.roger_value FROM testfirst) = (SELECT testall.roger_value FROM testall);
CALL proc_test(999, 'testvalue', 8888) ;
Status:
Failed
Error message
An error occurred in a triggered SQL statement in trigger "schema111.test2". Information returned for the error includes SQLCODE "-811", SQLSTATE "21000" and message tokens "".. SQLCODE=-723, SQLSTATE=09000, DRIVER=4.27.25
I am not sure what is happening after trying many sites but still no answer. Can anyone help?
If I divine your intention correctly, make the following changes:
Use the keyword new to refer to the row being inserted
Fix the syntax
Applying these points makes the delete:
DELETE FROM testfirst
WHERE roger_value = NEW.roger_value;
If the goal is to delete all rows from testfirst having the same ROGER_VALUE value as in the inserted row into testall, then:
CREATE OR REPLACE TRIGGER test2
AFTER INSERT ON testall
REFERENCING NEW AS N
FOR EACH ROW mode DB2SQL
DELETE FROM testfirst F
WHERE F.ROGER_VALUE = N.ROGER_VALUE
If the goal is to update some values in the inserted row only (and not in all table rows), then:
CREATE TRIGGER test1
BEFORE INSERT ON testall
REFERENCING NEW AS N
FOR EACH ROW mode DB2SQL
SET way_out = N.way_out + 1,
way_in = N.way_in + 1

Error : there is no parameter $1postgres sql

I am trying to insert data into table using below query. But it's working fine without parametrization but when I add parameter to query. It throws error there is no parameter $1.
Using nodejs to execute query.
INSERT INTO or(
json,id,ortatus,status,
qty,initial_qty,name,position,pled,
price,value,created_by,created_on,modified_on)
SELECT
$1,$2,$3,$4,$5,$6,$7,$8,$8,$10,$11,'0000000000',to_timestamp('${timestamp}'),
CURRENT_TIMESTAMP WHERE NOT EXISTS (SELECT ID FROM OR WHERE ID=$12)
ON CONFLICT DO NOTHING`,[`${Json}`,Id,orStatus,Status,
qty,initialQty,`${name}`,Position,pled,Price,Value,Id])

SQL query regarding Sequence

I made a sequence in Net Beans. But when I tried to insert data in the table I get an error.
My code is:
CREATE SEQUENCE seq_person
MINVALUE 1
START WITH 1
INCREMENT BY 1
INSERT INTO Persons (ID,FirstName,LastName)
VALUES (seq_person.nextval,'Lars','Monsen');
The error is:
[Exception, Error code 30,000, SQLState 42X04] Column
'SEQ_PERSON.NEXTVAL' is either not in any table in the FROM list or
appears within a join specification and is outside the scope of the
join specification or appears in a HAVING clause and is not in the
GROUP BY list. If this is a CREATE or ALTER TABLE statement then
'SEQ_PERSON.NEXTVAL' is not a column in the target table.
The error message Error code 30,000, SQLState 42X04 indicates you are using Derby DB not Oracle. That being the case you need to use Derby syntax for getting the next value. So your insert should look like this:
INSERT INTO Persons (ID,FirstName,LastName)
VALUES (NEXT VALUE FOR seq_person,'Lars','Monsen')

The MERGE statement attempted to UPDATE or DELETE error when executing stored procedure

I'm getting the following error message when attempting to use MERGE:
MMC.SOT_Load package failed to execute, stopped at Step 3 – stepname “SOT”
Code: 0xC002F210 Source: Yellow_Fields Execute SQL Task Description: Executing the query " DECLARE #RC int -- TODO: Set parameter values he..." failed with the following error: "The MERGE statement attempted to UPDATE or DELETE the same row more than once. This happens when a target row matches more than one source row. A MERGE statement cannot UPDATE/DELETE the same row of the target table multiple times. Refine the ON clause to ensure a target row matches at most one source row, or use the GROUP BY clause to group the source rows.". Possible failure reasons: Problems with the query, "ResultSet" property not set correctly, parameters not set correctly, or connection not established correctly.
This is the SQL I'm using:
MERGE MasterTable As Target
USING AcademicAffairs As Source
ON (Target.Life_Hosp = Source.Life_Hosp)
AND (Source.IsValid = 1)
AND (Target.IsValid = 1)
AND (Target.Life_Hosp is not Null And LEN(Target.Life_Hosp) > 0)
WHEN Matched Then Update
Set Target.DEA = COALESCE(NullIf(LTrim(RTrim(Source.DEA)),''), Target.DEA),
--Target.DPF = COALESCE(NullIf(LTrim(RTrim(Source.DPF)),''),Target.DPF),
Target.LastName = COALESCE(NullIf(LTrim(RTrim(Source.LastName)),''),Target.LastName),
Target.FirstName = COALESCE(NullIf(LTrim(RTrim(Source.FirstName)),''),Target.FirstName),
Target.License_Type = COALESCE(NullIf(LTrim(RTrim(Source.License_Type)),''),Target.License_Type)
;

DB2 SQL - Cannot successfully insert into table after trigger has been made

I have been running into problems inserting values into a table after having a trigger attached to it.
The trigger is the following:
CREATE TRIGGER trig
AFTER INSERT ON Follows
REFERENCING NEW as N
FOR EACH row
WHEN ((Select email from Celebrity) <> N.followed_email)
UPDATE followSuggestion SET followSuggestion.Suggested_follower = N.followed_email, followSuggestion.Suggested_followee = N.follower_email
;
the insert code is the following:
INSERT INTO follows
VALUES('Michael_Phelps#uss.net','Michael_Phelps#uss.net');
And the error is as follows
DB21034E The command was processed as an SQL statement because it was not a
valid Command Line Processor command. During SQL processing it returned:
SQL0811N The result of a scalar fullselect, SELECT INTO statement, or VALUES
INTO statement is more than one row. SQLSTATE=21000
SQL0811N The result of a scalar fullselect, SELECT INTO statement, or VALUES INTO statement is more than one row.
Thank you in advanced!
I think this is the problem:
(Select email from Celebrity) <> N.followed_email
The subquery will probably return more than one row so the scalar operator <> will not work.
You will have to rephrase that condition to something like:
WHEN ((Select COUNT(email) from Celebrity WHERE email = N.followed_email) = 0) ...