Can I use the 'WHERE' clause in an 'INSERT' command in SQLite3? - sqlite

I am using SQLite3 with Python. I am quite certain that the 'WHERE' clause does not work with 'INSERT' operation, but I really need to have a workaround to solve my issue. I have the following prepopulated database:
I was hoping to come up with an SQL statement where I can add the VALUES ('2021-01-13', '36.8') to the table WHERE family='FAA' AND model='MAA'. I have read a lot of stuff online but still no luck on my side.

I think you want an update here:
UPDATE yourTable
SET date = '2021-01-13', duration = 36.8
WHERE family = 'FAA' AND model = 'MAA';

You want to update your table, insert is only for new rows. When you want to change a value, you must to use update statement.
UPDATE table_name
SET date = '2021-01-13', duration = '36.8'
WHERE family='FAA' AND model='MAA';
https://www.sqlite.org/lang_update.html

Related

MariaDB Remove text from record

I have longtext data in data column as show by image, how to remove
{"current_id_position":"8861","targetted_id_position":"","count_new_technical":"0"}
for all record in 1 query? I just need number inside targetted_id_position
Thanks, hope u're helping me. I'm so confused what should I do.
Since the column contains JSON, you can use the JSON extraction operator.
UPDATE tableName
SET data = data->>'$.targetted_id_position'
MariaDB didn't copy MySQL's ->> operator, so you have to call the functions instead.
UPDATE tableName
SET data = JSON_UNQUOTE(JSON_EXTRACT(data, '$.targetted_id_position'))

How to Update Fields On Insert using Trigger

I've created and worked with Triggers in Oracle for years however I'm unable to wrap my head around how to update a field when inserting data into a sqlite database.
All I want to do is create a trigger that automatically inserts the current DateTime into a column in the sqlite database named 'createdDate' for ANY record that is inserted.
What is the best approach to accomplish this?
Below is what I've attempted without success.
CREATE TRIGGER outputLogDB_Created_Trig
BEFORE INSERT
ON outputLog
WHEN NEW.createdDate IS NULL
BEGIN
SELECT CASE WHEN NEW.createdDate IS NULL THEN NEW.createdDate = datetime('now', 'localtime') END;
END;
The above is almost a replica of how I would implement my triggers in Oracle with some modifications of course for sqlite. The logic is basically identical.
What am I missing?
Later Edit - I can get it to work if I instead use AFTER INSERT and not using FOR EACH ROW
CREATE TRIGGER outputLog_Created_Trig
AFTER INSERT
ON outputLog
WHEN New.createdDate IS NULL
BEGIN
UPDATE outputLog
SET createdDate = datetime('now', 'localtime')
WHERE outputLog_ID = New.rowid;
END;
But why can't I just insert the record using the new value while I'm inserting it? Am I ONLY able to get this in there using an Update AFTER I've already inserted the record?
The issue I have with this is the fact that I'd like to have a NOT NULL constraint on the createdDate column. Perhaps I'm simply used to how I've done it for years in Oracle? I realize the Trigger 'should' take care of any record and force this field to NEVER be NULL. It's just that NOT being able to add the constraint for some reason makes me uneasy. Do I need to let go of this worry?
Thanks to Shawn pointing me toward an easy simple solution to my problem. All that is needed in a SQLite database to insert the current Date/Time for each record being inserted is to set the DEFAULT value on that column to CURRENT_TIMESTAMP.
Since I wanted the timestamp in my own local time see below my create table script that is the solution to my problem.
CREATE TABLE outputLog (
outputLog_ID INTEGER PRIMARY KEY ASC ON CONFLICT ROLLBACK AUTOINCREMENT
NOT NULL ON CONFLICT ROLLBACK,
outputLog TEXT,
created DATETIME DEFAULT (datetime(CURRENT_TIMESTAMP, 'localtime') )
NOT NULL )
;

PL/SQL Trigger exercise

I have this question that I can see what it's asking but just can't wrap my head around how to write it specifically:
When a new tuple is inserted into the sales order detail, your trigger should insert a corresponding raw material tuple in the Inventory Report table for the Report date (i.e., beginning inventory level, consumption quantity, same-day order quantity, next-day order quantity)
Assumptions I gathered from the notes:
itemID = itemID from RAWMATERIALS table
reportDate = dueDate from SALESORDERS table
begInv = inventoryLevels from RAWMATERIALS table
consumpQty = itemID from FINISHEDGOODS * rmQuantity (raw material required to make each finished good) from FINISHED GOODS
orderNextDay = If consumpQty <= begInv then orderNextDay = consumpQty
orderSameDay = 0
orderSameDay = If consumpQty > begInv then orderNextDay = begInv
orderSameDay = consumpQty - begInv
I thought the trigger might go something like:
CREATE OR REPLACE TRIGGER inv_report
BEFORE INSERT
ON SALESORDERDETAIL
FOR EACH ROW
DECLARE
item_id RAWMATERIALS.ITEMID%TYPE
reportDate SALESORDERS.DUEDATE%TYPE
begInv RAWMATERIALS.INVENTORYLEVEL%TYPE
And then I understand we would probably need to INSERT into INVENTORYREPORT table (which currently has no data in it) and maybe do an IF ELSEIF statement to satisfy the orderNextDay and orderSameDay columns but i'm still not familiar enough with PL/SQL to know exactly how to tackle this.
Can anyone help me out with this? Thanks!
I'll try to find some time to write up some code for you on this, but my first recommendation is to NOT do this in a trigger. Instead, create a procedure "insert_so_detail" that inserts into the the SALESORDERDETAIL and then does the related insert into INVENTORYREPORT.
That procedure is then always called to insert into the S-O-D table. Executing DML inside triggers is a tricky thing to do because the database might decide it needs to restart the DML and then possibly do another insert into the I-R table. Check out this AskTOM thread for more details.
You are always better off putting your DML into PL/SQL package APIs, then only allow DML on the table through the API (grant execute on the package, do NOT grant insert or update or delete on the table directly to a user).

PLSQL: How to update and Insert together when match found between source and target table

I have a source and a target table. I need to make update and insert together in final table with following conditions:
1) When SourceTable.ProductName = TargetTable.ProductName and SourceTable.Amount = TargetTable.Amount Then
Update TargetTable set TargetTable.ValidFrom = sysdate
Also i need to insert like this,
Insert Into TargetTable(ProductName,Amount,ValidFrom,Version) Values(TargetTable.ProductName,TargetTable.Amount, sysdate, TargetTable.Version + 1)
This is to maintain version.
2) When there is no match then i need to insert directly like this,
Insert Into TargetTable(ProductName,Amount,ValidFrom,Version) Values(SourceTable.ProductName,SourceTable.Amount, sysdate,1)
As of now i am thinking of capturing these matching records in a Cursor and perform Update and Insert together in cursor loop. But i am willing to avoid loops a i have approx 10 millions of matching records.
We also have Merge statement, but I believe Merge do not support Update and Insert together in single "WHEN MATCHED" Clause. Please correct me if i am wrong?
Kindly suggest the best way to achieve this behavior.

asp.net InsertCommand to return latest insert ID

I'm unable to retrieve the latest inserted id from my SQL Server 2000 db using a typed dataset in asp.NET
I have created a tableadapter and I ticked the "Refresh datatable" and "Generate Insert, Update and Delete statements". This auto-generates the Fill and GetData methods, and the Insert, Update, Select and Delete statements.
I have tried every possible solution in this thread
http://forums.asp.net/t/990365.aspx
but I'm still unsuccesfull, it always returns 1(=number of affected rows).
I do not want to create a seperate insert method as the auto-generated insertCommand perfectly suits my needs.
As suggested in the thread above, I have tried to update the InsertCommand SQL syntax to add SELECT SCOPY_IDENTITY() or something similar, I have tried to add a parameter of type ReturnValue, but all I get is the number of affected rows.
Does anyone has a different take on this?
Thanks in advance!
Stijn
I decided to give up, I can't afford to waste any more time on this.
I use the Insert statement after which I do a select MAX(id) query to hget the insert ID
If anyone should have a solution, I'll be glad to read it here
Thanks
Stijn
I successfully found a way to get the incremental id after insert using my table adapter.
My approach is a little different, I'm using a Store procedure to make the insert, so my insert command has all the values but the ID, I made the sp return the ID just calling:
SET #ID=SCOPE_IDENTITY()
and then
COMMIT TRAN
and last line will be
RETURN #ID
Then I searched my table adapter parameters for InsertCommand and set the #RETURNVALUE to the column of the incremental ID of the table, so when it's executed automatically put the return value on the id field.
Hope this help
You need to tell your table's table-adapter to refresh the
data-table after update/insert operation.
This is how you can do that.
Open the properties of TableAdapter -> Default Select Query -> Advnaced options. and Check the option of Refresh the data table. Save the adapter now. Now when you call update on table-adapter, the data-table will be updated [refreshed] after the update/insert operation and will reflect the latest values from database table. if the primary-key or any coloumn is set to auto-increment, the data-table will have those latest value post recent update.
Now you can Call the update as TableAdapterObj.Update(ds.dataTable);
Read latest values from the DataTable(ds.dataTable) coloumns and assign respective values into the child table before update/insert. This will work exactly the way you want.
alt text http://ruchitsurati.net/files/tds1.png

Resources