Convert SQL to PL/SQL For "IF NOT EXISTS" - sql

I have some SQL code that I want to convert into PL/SQL for Oracle, however I'm struggling to find a good alternative for the "IF NOT EXISTS" function. Can someone help?
Here's the SQL that needs converting:
IF NOT EXISTS (SELECT * FROM SEC_ConfigSetting WHERE ItemKey='Version')
BEGIN
INSERT INTO SEC_ConfigSetting
([VersionNo]
,[Section]
,[ItemKey]
,[ItemValue]
,[ItemType])
VALUES
(1,4,'Version','V1.4.0',0)
END
ELSE
BEGIN
/* Update database version */
UPDATE [SEC_ConfigSetting]
SET [ItemValue] = 'V1.4.0'
WHERE ItemKey='Version'
END

What you're doing looks like you need merge
merge into SEC_ConfigSetting s
using (select 1 VersionNo, 4 Section,'Version' ItemKey,'V1.4.0' ItemValue, 0 ItemType from dual) d
on (s.ItemKey = d.ItemKey)
when matched then update set
ItemValue = d.ItemValue
when not matched then
INSERT (VersionNo, Section,ItemKey,ItemValue,ItemType)
VALUES (d.VersionNo, d.Section, d.ItemKey, d.ItemValue, d.ItemType);
And this can be used as a plain SQL or as part of PL/SQL script.

Related

Snowfalke sql update if exists else insert

I have looked at other question but seems that snowflake doesn't support if/else in sql, at least not the way that other sql servers support it.
some suggested to use javascript but i would like to avoid that if I can.
I am trying to Insert into a table using snowflake python library some data, if it's already there then I would like to update the data, I have looked at merge but it doesn't seem to fit me since my data isn't a table
that's what I have so far that isn't working
f"""BEGIN
IF (EXISTS (SELECT * FROM {self.okr_table} WHERE kpi=TRUE AND Month(month)=MONTH(current_date()) AND year(month)=YEAR(current_date())))
THEN
UPDATE {self.okr_table} SET [DATA] = {json.dumps(self.data)} WHERE kpi=TRUE AND Month(month)=MONTH(current_date()) AND year(month)=YEAR(current_date()))
ELSE
INSERT INTO {self.okr_table} (month, data, kpi) SELECT current_date(),parse_json('{json.dumps(self.data)}'), true;
END"""
To perfrom INSERT/UPDATE it is better to use single MERGE statement
I have looked at merge but it doesn't seem to fit me since my data isn't a table
It is not an issue as source could be a table or subquery:
MERGE INTO {self.okr_table}
USING (SELECT PARSE_JSON({json.dumps(self.data)} AS data
, MONTH(current_date()) AS month
, YEAR(current_date()) AS year
) s
ON {self.okr_table}.KPI
AND MONTH({self.okr_table}.month) = s.month
AND YEAR({self.okr_table}.month) = s.year
WHEN MATCHED THEN UPDATE
WHEN NOT MATCHED THEN INSER ...;
IF/ELSE branching works in Snowflake:
BEGIN
IF (EXISTS (...)) THEN
UPDATE ... ;
ELSE
INSERT ... ;
END IF;
END;
Please note ; after each statement, END IF and parenthesis around condition.

with sql how can i insert data but if it's already exists update data

I want to add it - if exists update else insert!
so that insert is working but i want to only insert new value and if thing already here i want to update it. my code here only inserts data no metter what
BEGIN
DECLARE das int;
SELECT dasaxeleba.id INTO das FROM dasaxeleba WHERE dasaxeleba.barcode = NEW.barcode;
INSERT INTO sawyobi(das_id,raodenoba,tvitgirebuleba,gasayidi1,gasayidi2)
VALUES(das,new.raodenoba,new.fasi,new.gasayidi1,new.gasayidi2);
END
if you are using oracle then you can use something like that:
merge into sawyobi tgt
using (select id
from dasaxeleba
where barcode = NEW.barcode) src on (tgt.das_id = src.id)
when matched then update set
raodenoba = new.raodenoba,
tvitgirebuleba = new.fasi,
gasayidi1 = new.gasayidi1,
gasayidi2 = new.gasayidi2
when not matched then insert
(das_id,
raodenoba,
tvitgirebuleba,
gasayidi1,
gasayidi2)
values (src.id,
new.raodenoba,
new.fasi,
ew.gasayidi1,
new.gasayidi2)
not quite sure where your "new"-values come from... but i hope you get the idea

Merge statement for first time insert

I did some research and couldn't find any solution and hence posting it here.
We have a dataload job which runs on a daily basis. We have separate DML statements to insert, update etc. We wanted to avoid insert statements to run multiple times.
Is there an option to use merge statement in this scenario to update if the record is present or insert if not present?
Please give me an example if possible as I am quite new to sql statements.
We are using Oracle db2 for dbms
Thanks in advance!
Use an IF EXISTS statement, like this:
IF EXISTS (SELECT 1 FROM #mytable# WHERE #column1# = #this# AND #column2# = #that)
BEGIN
#update statement#
END
ELSE
BEGIN
#insert statement#
END
EDIT:
the syntax for this can be found here: https://www.toadworld.com/platforms/ibmdb2/w/wiki/7777.ifthenelse
this means that my general case would become this in DB2:
IF (#count of value# = 1) THEN
#updatestatement#;
ELSEIF (#count of value# > 1) THEN
#throw an error, as you cannot update uniquely#
ELSE
#insertstatement#;
END IF;
I also noticed that you can run SQL commands on DB2, which might be useful for this task as well
finally, have a look here, might give you further ideas :)
DB2 for IBM iSeries: IF EXISTS statement syntax
Got it done throught Merge statements itself :)
MERGE INTO table1(storeent_id, name, value) AS t1
USING (VALUES ((SELECT STOREENT_ID FROM STOREENT WHERE IDENTIFIER='test'), 'SOLR_SERVICEABILITY_URL',
'Sample')) AS t2(storeent_id, name, value)
ON t1.name = t2.name AND t1.storeent_id = t2.storeent_id
WHEN MATCHED THEN
UPDATE SET
t1.value = t2.value
WHEN NOT MATCHED THEN
INSERT
(name, storeent_id, value)
VALUES (t2.name, t2.storeent_id, t2.value);

Update or otherwise create an entry in table

I want to update or create a new entry in a table with normal SQL (not MySQL).
My table has columns: T_ID, ITERATION, COMMENT
I know that I can update my table with:
UPDATE TABLE
SET ITERATION = ITERATION + 1
WHERE T_ID = 1;
But if no entry with T_ID = 1 exists I want to create an entry with ITERATION = 1 and T_ID = 1 and as COMMENT nothing.
Is this possible by using a normal SQL statement?
Is this possible by using a normal SQL statement?
No - there is no "standard" SQL construct for an "upsert" (or Merge) in one statement. Different SQL systems have implemented mechanism to perform an "update if exists" operation, such as MySQL's ON DUPLICATE KEY UPDATE or Oracle and SQL Server's MERGE syntax, but nothing in "standard" SQL.
You would want to do it in a stored procedure. Something like this where you're checking to see if anything exists where T_ID = 1. Then based off that conclusion you'll either update or insert.
BEGIN TRAN
IF EXISTS (SELECT * FROM table WHERE T_ID = 1)
BEGIN
UPDATE table SET ITERATION = ITERATION + 1 WHERE T_ID = 1
END
ELSE
BEGIN
INSERT INTO table (T_ID, ITERATION, COMMENT)
VALUES (1, 1, '')
END
COMMIT TRAN

UPSERT in SQLite

I don't want to use REPLACE INTO because it's basically a DELETE and INSERT and it's complicated to use the data from the old columns.
INSERT OR IGNORE is a bit of a hack because all errors are ignored, so this is not an option.
I've read a blog article which uses the following:
UPDATE Table1 SET (...) WHERE Column1='SomeValue'
IF ##ROWCOUNT=0
INSERT INTO Table1 VALUES (...)
I like this approach really much, but I don't know how I can implement this IF-clause with the ##ROWCOUNT in SQLite, this is what I got:
SELECT CASE (SELECT
CASE
WHEN EXISTS(SELECT 1 FROM t WHERE id=2)
THEN 1
ELSE 0
END)
WHEN 1
UPDATE t set a='pdf' WHERE id=2;
ELSE
INSERT INTO t (a) VALUES ('pdf');
END
the SELECT CASE seems to be the only way to use a CASE-clause in SQLite because everything else throws an syntax error. But it's also not possible to use a UPDATE- or INSERT-statement in the SELECT CASE, so this throws an error.
I've tried the following
UPDATE t set a='pdf' WHERE id=2;
CASE WHEN (changes()=0) THEN
INSERT INTO t (a) VALUES ('pdf');
END
but this doesn't work, because the CASE-clause throws an syntax error.
can someone provide an example using ##ROWCOUNT for an UPSERT in SQLite?
SQLite has no built-in UPSERT-like statement that doesn't delete the old record.
You should check the number of changes in your program, and execute the INSERT conditionally.
However, if you really want to do this in SQL, it's possible; but you have to use the INSERT ... SELECT ... form so that you are able to insert zero records, if needed:
BEGIN;
UPDATE t SET a = 'pdf' WHERE id = 2;
INSERT INTO t(id, a) SELECT 2, 'pdf' WHERE changes() = 0;
COMMIT;
You should use sqlite API in this case and write "IF logic" in your application.
sqlite3_prepare16_v2(stmt1, "UPDATE t SET a=? WHERE id=?");
sqlite3_prepare16_v2(stmt2, "INSERT INTO t(id, a) VALUES(?, ?)");
for(...) // iterate by rows to be updated/inserted
{
//set parameter values for stmt1
sqlite3_step(stmt1);
if( !sqlite3_changes(dbh) )
{
//set parameter values for stmt2
sqlite3_step(stmt2);
}
}