SQL Server: IF EXISTS statement - sql

I am working on an If Exists Then Update, Else Insert statement in SQL Server and have 2 questions.
First, I was hoping to be able to debug my statement by effectively having it perform two steps:
If Exists (select.....)
Print 'Record already exists'
UPDATE Tab set Col....
Which fails. Is there a way to get both statements to execute or can I only have one result when If Exists returns TRUE? I tried a comma after the PRINT command but that made no difference.
Second, my If Exists query returns one record (for now). But, running my UPDATE without a WHERE clause causes every record in the Table to be changed. I thought the UPDATE would operate only on the records returned by the If Exists test. Do I need to specify a WHERE clause in my UPDATE statement, much like I would if I had no If Exists test?

The sintax that you need should be the next:
if exists (select ... _your_condition_)
begin
Print 'Record already exists'
UPDATE Tab set Col....
end
else
begin
Print 'New record'
INSERT into Tab ....
end
Remark that without begin/end blocks, the if applies just the immediate next sentence, so the update would be done always in your example.
This is just one answer to one part of your question, which is quite misleading. If your WHERE filter has some relationship with the check that you are performing in the "if exists" sentence, we should know it exactly to know if there is a better way to resolve your query.

Related

Update A Record if it exists, else do nothing, including short-cicruit

What I want to do is something that has the following logic:
IF EXISTS (SELECT * FROM people WHERE ID = 168)
THEN UPDATE people SET calculated_value = complex_queries_and_calculations
WHERE ID = 168
.., so to update a field of a given record if that record contains a given data, and else do nothing. To generate the data which would be used for the update, I need to query other tables for values and make some calculations. I want to avoid these queries + calculations, if there's actually nothing to update. And in this case, simply do nothing. Hence, I guess that putting for example an EXIST clause inside a WHERE clause of the UPDATE statement would end in many queries and calculations made in vain.
How can I only UPDATE conditionally and else do nothing, and make sure that all the queries + calculations needed to calculate the value used for the update are only made if the update is needed? And then, in the end, only do the update if complex_queries_and_calculations is not NULL?
My best solution so far uses a Common Table Expression (WITH clause), which makes it impossible to short-circuit. Anyway, such that you can understand the logic I'm trying to achieve, I'm showing what I've been trying so far (without success; code below is not working and I don't know why..):
-- complex queries and calculations; return result as t.result
WITH t AS(complex queries and calculations)
UPDATE target_table
SET
CASE
WHEN t.result IS NOT NULL
THEN target_table.target_column = t.result WHERE target_table.PK = 180
END;
UPDATES (Still saying syntax error, still not working)
WITH t AS(complex_queries_and_calculations AS stamp)
UPDATE target_table
SET target_column =
CASE
WHEN t.stamp IS NULL
THEN target_column
ELSE t.stamp
END
WHERE ID = 168;
Not even this is working (still reporting syntax error on UPDATE line):
WITH t AS(complex_queries_and_calculations AS stamp)
UPDATE target_table
SET target_column = target_column
WHERE ID = 168;
(eventual better approaches which avoid redundant target_column = target_column updates welcome)
With select it works, so I'm totally not understanding the syntax error #1064 it returns for my update query:
WITH t AS(complex_queries_and_calculations AS stamp)
SELECT
CASE
WHEN t.stamp IS NULL
THEN "Error!"
ELSE t.stamp
END
FROM t;
ADDITIONAL INFO
It seems like MariaDB actually does not support CTEs with UPDATE statements; correct me if I'm wrong... So I tried the following:
UPDATE people AS p
INNER JOIN (queries_and_calculations AS result) t
ON p.ID <> t.result -- just to join
SET p.target_column = t.result
WHERE p.ID = 168
AND t.result IS NOT NULL;
and now it's saying:
#4078 - Illegal parameter data types varchar and row for operation '='
Simply do the UPDATE. If there is no row with that ID, it will do nothing. This will probably be no slower than testing first.
Ditto for DELETE when the row might not exist.
"Upsert"/"IODKU" -- INSERT ... ON DUPLICATE KEY UPDATE ... is useful when you want to modify some columns when the row exists (according to some unique column), or add a new row (when it does not exist). This is better than doing a SELECT first.
Think of it this way... A big part of the UPDATE is
opening the table,
locating the block in the table that needs to be modified
loading that block into the cache ("buffer_pool")
All of that is needed for both your SELECT and UPDATE (yeah, redundantly). The UPDATE continues with:
If the row does not exist, exit.
Modify the row, and flag the block as "dirty".
In the background, the block will eventually be flushed to disk.
(I left out details about transactional integrity ("ACID"), etc.)
Even in the worst case, the whole task (for a single row) takes under 10 milliseconds. In the best case, it takes under 1ms and can be done somewhat in parallel with certain other activities.
There is no IF in SQL, since it is not needed:
UPDATE people p
SET calculated_value = c.val
FROM (
SELECT ID, val
FROM
... complex_queries_and_calculations
) c
WHERE c.ID = p.ID
AND ID = 168
AND v.val <> i.val -- maybe add this to avoid idempotent updates. Beware of NULLs, though!
;
~
GOT IT, The following query works to do exactly what I wanted in Mariadb :
UPDATE target_table
LEFT JOIN (complex_queries_and_calculations_to_get_update_value AS update_value) t
ON target_table.ID <> t.update_value -- serves just to have update value in memory,
-- because it needs to be accessed twice to create the updated column value
-- on update, sort of a workaround for CTE + UPDATE in MariaDB
SET target_column = JSON_ARRAY( FORMAT_UPDATE_VALUE(t.update_value),
FORMAT_2_UPDATE_VALUE(t.update_value) )
WHERE ID = 128 AND t.update_value IS NOT NULL;
If the record does not exist, the query takes about 0.0006 secs to execute, without doing anything to the table. If it does exits, it takes 0.0014 secs to execute, while updating the targeted record accordingly. So, it indeed seems to work and resources are saved if the targeted record is not found in target_table. Great thanks to all who helped!

How do you query table for containing a value

I want to know if a table contains at least one entry that meets specific conditions. I don't want to go over all entries but to stop at first one. Is there a generic way to do this in sql?
I think a research would have given you the answer much more quickly, but anyway here is what I use:
IF EXISTS (SELECT NULL FROM Table WHERE Field = #value)
BEGIN
PRINT 'Exists!'
END
ELSE
BEGIN
PRINT 'Does not exist!'
END
Bear in mind that when using EXISTS, it doesn't matter what fields you select, whether they are from the table, constants or even NULL values as in this case.

Can I block an insert inside a trigger on Oracle 11g?

So, what I want to do is to block an insert if the condition is met. In this case, I'm developing a simple library database system and I don't want to allow someone to be able to borrow a book if that certain person has already borrowed 2 books and still hasn't returned any of them.
I need to do this via trigger, is it possible? Also, I'd like to know if I can supply a query into the WHEN clause like I did.
CREATE OR REPLACE TRIGGER trigger_borrowing_limit
BEFORE INSERT ON Borrowing
REFERENCING NEW ROW AS NROW
FOR EACH ROW
WHEN SELECT COUNT(*) FROM Borrowing WHERE RETURN_DATE IS NULL AND NROW.ID = Borrowing.ID > 2
BEGIN
?
END
You can't supply a query for the WHEN clause. From the Oracle 11 docs (search for "WHEN (condition)" once you get to the page):
Restrictions on WHEN (condition)
If you specify this clause, then you must also specify FOR EACH ROW.
The condition cannot include a subquery or a PL/SQL expression (for example, an invocation of a user-defined function).
As for preventing the row insert, the comment from Mihai is the way to go. Your front end can catch the exception, and if it's error number -20101 (per Mihai's example) you'll know that the person already has two books out. Note that some drivers will report the absolute value of the exception number, so the error number that reaches you may be 20101.
Addendum: a followup question asked how to apply the "two books out" logic since it's not valid for the WHEN clause.
The answer is to drop the WHEN clause and put the logic into the trigger body. Note that I normally stick with the standard NEW for referencing the new row, so my answer doesn't have the REFERENCING NEW AS NROW:
CREATE OR REPLACE TRIGGER trigger_borrowing_limit
BEFORE INSERT ON Borrowing
DECLARE
booksOut NUMBER;
BEGIN
SELECT COUNT(*) INTO booksOut
FROM Borrowing
WHERE RETURN_DATE IS NULL AND NEW.ID = Borrowing.ID;
IF booksOut > 2 THEN
-- Next line courtesy of Mihai's comment under the question
raise_application_error(-20101, 'You already borrowed 2 books');
END IF;
END;

"Update if table exists" in one statement - how?

I have a problem with SQL statement which is a part of long transaction.
UPDATE tab_1
LEFT JOIN tab_2
ON tab_1.id = tab_2.tab_1_id
SET tab_1.something = 42
WHERE tab1.id = tab_2.tab_1_id;
Everything is simple and works fine as long as tab_1 and tab_2 exist in database, which is obvious. ;-)
The problem is that the transaction have to be commited on 4 different servers, and tab_2 is "dynamic" table, which may exist in specific db / db schema, or not...
If tab_2 don't exists, database threw exception and the whole transaction is not commited. What I want is to continue anyway (just update 0 rows)!
I have tried something like this:
UPDATE [all the same as above] WHERE tab1.id = tab_2.tab_1_id AND EXISTS (select 1 from pg_class where relname='tab_2');
...but it's still wrong, since "exception-check" is made before "where" condition (it's the same table we want to use in join..).
Is there any way to do this with "pure" SQL? :)
Something like: LEFT JOIN tab_2 IF tab_2 EXISTS (and if not - do nothing, return null, etc.?)
I know there is a way to do this in pl/pgsql procedure.
The second possibility is to create table if not exists, before the statement..
But maybe there is some kind of simple and elegant way to do this in one statement? :)
DBMS: PostgreSQL 9.2
I don't think an UPDATE statement that succeeds even if a table doesn't exist is simple and elegant. I think it is strange and confusing.
Why not just include a conditional that checks whether that table exists, and only perform the update if it exists? It would be a lot clearer.
Another option would be to create a view that points to tab_2 if it exists, or points to an empty table otherwise. This could be helpful if you have a lot of queries like this, and you don't want to change them all.
Update: Here is what a condition would look like (has to be within a function or a BEGIN...END block):
IF EXISTS (select 1 from pg_class where relname='tab_2') THEN
UPDATE...
END IF;
Depending on the details of Postgresql, this still might fail compilation if it sees a table that doesn't exist in the UPDATE statement (I'm not a Postgresql user). In that case, you would need to create a view that points to tab_2 if it exists, and an empty table if it doesn't exist..

How to specify an ELSE condition with WHEN?

Given this code (pseudo)
MERGE INTO ...
(SELECT ... FROM ...) ...
ON (...)
WHEN NOT MATCHED THEN
INSERT (...) VALUES (...);
//This is Oracle Apex code
apex_application.g_unrecoverable_error := true;
htp.init();
owa_util.redirect_url('f?p=111:11:&APP_SESSION.::NO:::');
How would add a condition so that when it doesn't match it, I need to run this line of code:
apex_application.g_notification := 'My error';
I am not sure what to do to make it work. I tried some ELSE and additional WHEN statements but it doesn't seem to work.
As far as I am aware you will not be able to extend the MERGE statement in this way. You can take a count of of table being inserted into before and after to determine whether any rows fell into the NOT MATCHED section and got inserted.
Put your logic in an IF statement using that count.
In a MERGE statement depending on the ON cond
you issue a UPDATE and optionally DELETE if MATCHED
you issue a INSERT if NOT MATRCHED
Your apex code can not be part of the MERGE statement. You have to figure out a different strategy for it.