SQL query regarding Sequence - sql

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')

Related

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

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.

Setting Triggers in Maria DB

I am trying to set the trigger in maria db
The query which I am running is
CREATE TRIGGER TEMP
AFTER INSERT
ON sample_details FOR EACH ROW
BEGIN
UPDATE SAMPLE_MONITOR SET TableDataCount= TableDataCount+ 1,Time=NOW() WHERE
TableName='sample_details';
END; //
delimiter ;
I have a table named 'sample_details' there If any insert is done to that table, I want to increment the count in the row present in SAMPLE_MONITOR table by 1 and also insert the current time
But I am getting the following error after running query
ERROR 1064 (42000): 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 1
So anyone know how to solve this?

Python pyODBC : Issue inserting into a sql server table with an identity column

An INSERT statement that was created with Python gives me an error when I execute and commit it. I have taken a copy of the statement from Python and run it myself in SQL SERVER and it works fine there. The table I am trying to insert into has an identity column. When Python trys to execute it will give me an error saying what is below when I exclude the identity column in the statement
Table looks like this MY_TABLE ( ID INT IDENTITY(1,1) NOT NULL, A INT, B INT)
INSERT INTO MY_TABLE (A, B) VALUES(VALUE_A, VALUE_B);
"('23000', "[23000] [Microsoft][ODBC SQL Server Driver][SQL Server]Cannot insert the value NULL into column 'MY_IDENTITY_COLUMN', table 'MY_TABLE'; column does not allow nulls. INSERT fails. (515) (SQLExecDirectW); [23000] [Microsoft][ODBC SQL Server Driver][SQL Server]The statement has been terminated. (3621)")"
But when I try to include the value for the Identity column (I don't want to do this) I get the following error which makes sense as it's an identity column that we let the table auto-increment
"Cannot insert explicit value for identity column in table 'MY_TABLE' when IDENTITY_INSERT is set to OFF."
When I run the query in SQL SERVER the table fills the value for the Identity Column itself and auto-increments but for some reason when I run the statement in Python it does not do this and tries to pass a NULL
SQL SERVER version: 10.50.6560.0
Recognising it's a little late but... I had the same problem recently using some old program and ODBC. The solution was to create a View in SQL Server with only the columns required (i.e. A and B in your case) and then insert into that View.
A little hard to tell without your code, but here is an example.
In database create a test table
CREATE TABLE dbo.test(
ID INT IDENTITY NOT NULL PRIMARY KEY,
Name VARCHAR(40) NOT NULL
);
Then in Python specify the columns you are inserting into
import pyodbc
warecn = pyodbc.connect("Your Connection Stuff")
Inscursor = warecn.cursor()
Inscursor.execute("Insert into dbo.test(name) values ('This'), ('is'), ('a'), ('test')")
Inscursor.commit()
Inscursor.close()
del Inscursor
warecn.close()

Create Transaction on MariaDB to set expiry time for ip blacklist

The question I used to help build this transaction is here:
How to add 1 hour to currrent_timestamp in mysql which is the default value?
I'm trying to create a transaction in my database to fill in the allowed column in my mariadb database table blacklisted_ips. I want the allowed column to be an hour after my added column which has a default value of CURRENT_TIMESTAMP. Here is my transaction so far:
CREATE TRIGGER before_insert_on_blacklisted_ips BEFORE INSERT ON blacklisted_ips FOR EACH ROW BEGIN
SET NEW.allowed=NOW()+INTERVAL 1 HOUR;
END;
The error message I'm getting is the following:
#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 2
Here is my table schema:
CREATE TABLE blacklisted_ips (
ip_id int(11) NOT NULL AUTO_INCREMENT,
ip_add varchar(15) NOT NULL,
added timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
allowed timestamp NOT NULL,
PRIMARY KEY (ip_id)
);
In MySQL, there's an ambiguity between the ; that terminates a CREATE TRIGGER statement, and the possible ; characters that terminate individual statements in the body of the trigger.
The error you got is confusing:
#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 2
Normally a syntax error includes the text of the statement following the position where the syntax parser got confused. But in your case, it got confused at ;, thinking it was the end of the CREATE TRIGGER statement. Therefore the error occurs at the termination; there is no text following the error as far as the parser is concerned.
The same issue affects CREATE PROCEDURE and CREATE FUNCTION.
To fix the ambiguity, MySQL client supports a builtin command to change the DELIMITER, so you can change it to something distinct from any sequence of characters that appear in the body of your routine.
DELIMITER ;;
CREATE TRIGGER before_insert_on_blacklisted_ips BEFORE INSERT ON blacklisted_ips
FOR EACH ROW BEGIN
SET NEW.allowed=NOW()+INTERVAL 1 HOUR;
END ;;
Alternatively, since in your case the trigger is a single-statement trigger, you don't need a BEGIN...END block at all. This way you can skip changing the DELIMITER, because the ; that terminates your CREATE TRIGGER is the same ; that terminates the single statement of the trigger.
CREATE TRIGGER before_insert_on_blacklisted_ips BEFORE INSERT ON blacklisted_ips
FOR EACH ROW
SET NEW.allowed=NOW()+INTERVAL 1 HOUR;
P.S.: This is documented with an example here: https://dev.mysql.com/doc/refman/8.0/en/trigger-syntax.html

IDENTITY_INSERT error while trying to insert data into table

I want to copy data from a table named ActionType inside a database TD_EDD, into another table named ActionType inside another database DsVelocity.
I have written the following query:
INSERT INTO [DsVelocity].[dbo].[ActionType]
([ActionTypeID]
,[ActionTypeName]
,[ActiveStatus])
SELECT [ActionTypeID], [ActionType], [Active/Deactive]
FROM [TD_EDD].[dbo].[ActionType]
GO
Whenever I'm trying to do this, I'm getting the following error:
Msg 544, Level 16, State 1, Line 1
Cannot insert explicit value for identity column in table 'ActionType' when IDENTITY_INSERT is set to OFF.
I don't understand what's wrong and why I'm getting this error?
Note that I'm using Microsoft SQL Server 2008 R2.
This means that when you insert data into target table, you will have conflicting ids. Most likely ActionTypeId column
to Fix it use
INSERT INTO [DsVelocity].[dbo].[ActionType]
([ActionTypeName]
,[ActiveStatus])
SELECT [ActionType], [Active/Deactive]
FROM [TD_EDD].[dbo].[ActionType]
GO
Well, lets assume from the message that ActionTypeID is an IDENTITY Column. You cannot isert values into this column as it is auto generate, uless you use IDENTITY_INSERT
Allows explicit values to be inserted into the identity column of a
table.
At any time, only one table in a session can have the IDENTITY_INSERT
property set to ON. If a table already has this property set to ON,
and a SET IDENTITY_INSERT ON statement is issued for another table,
SQL Server returns an error message that states SET IDENTITY_INSERT is
already ON and reports the table it is set ON for.
If the value inserted is larger than the current identity value for
the table, SQL Server automatically uses the new inserted value as the
current identity value.
The setting of SET IDENTITY_INSERT is set at execute or run time and
not at parse time.
So you would have to do something like
SET IDENTITY_INSERT [DsVelocity].[dbo].[ActionType] ON
before the insert.