简体   繁体   English

Oracle SQL:UPDATE,但如果不满足条件,则抛出“错误”

[英]Oracle SQL: UPDATE, but throw 'error' if condition not met

Sorry if this is a dupe -- I searched for similar questions, but they all seemed to be along the lines of conditional updates where you can use CASE statements to set a column to one of several values. 抱歉,这是骗人的-我搜索了类似的问题,但它们似乎都遵循条件更新的原则,您可以在其中使用CASE语句将列设置为多个值之一。

I've got a SQL UPDATE statement, but there are two reasons why I would want it to NOT update: 我有一条SQL UPDATE语句,但是有两个我为什么不希望它更新的原因:

  1. the item isn't found (causing rowsUpdated to be 0) 找不到该项目(导致rowsUpdated为0)
  2. if a condition is met 如果满足条件

I'd like to differentiate between these two states somehow, which is why I can't just put the condition in the WHERE clause. 我想以某种方式区分这两个状态,这就是为什么我不能只将条件放在WHERE子句中的原因。

It currently looks something like this: 当前看起来像这样:

UPDATE MY_TABLE t 
   SET t.TITLE = :TITLE,
       t.TYPE = :TYPE,
       t.STATE = :STATE,
       t.UPDTIME = :UPDTIME
 WHERE t.ITEM_ID = :ITEM_ID 
   AND exists (SELECT t.ITEM_ID
                FROM MY_TABLE t, USERINFO ui
               WHERE ui.USERID = t.USERID
                 AND ui.USERNAME = :USERNAME
                 AND t.ITEM_ID = :ITEM_ID);

That will return 1 if it finds (and updates) an item in MY_TABLE that matches the given USERNAME and ITEM_ID, or 0 if it doesn't. 如果在MY_TABLE中找到(并更新)与给定的USERNAME和ITEM_ID匹配的项,则返回1;否则,返回0。

I'd like to add something so that it doesn't update if t.STATE = 'READ_ONLY' , but so that it does something to differentiate that condition from the "that item doesn't exist" condition. 我想添加一些内容,以便在t.STATE = 'READ_ONLY'它不会更新,但是为了使该条件与“该项目不存在”条件区分开来。 Maybe throw an error of some sort? 也许会抛出某种错误?

I could run a SELECT statement before my update to make sure that item's state isn't READ_ONLY, but that seems wasteful. 我可以在更新前运行SELECT语句,以确保该项目的状态不是READ_ONLY,但这似乎很浪费。 Is there a better way? 有没有更好的办法?

I don't think it's wasteful a previous SQL. 我认为先前的SQL并不浪费。 It would be confusing throwing an error just to catch a condition (what if your real update threw the same divided by zero error?). 仅仅为了捕获一个条件而抛出一个错误将是令人困惑的(如果您的实际更新将相同的错误除以零错误会怎样?)。 You could select for update, and update it by rowid afterwards to speed things up if your are using a heap table: 您可以选择进行更新,然后使用rowid更新它,以加快使用堆表的速度:

SELECT t.ITEM_ID, t.condition, t.rowid
FROM MY_TABLE t, USERINFO ui
WHERE ui.USERID = t.USERID
AND ui.USERNAME = :USERNAME
AND t.ITEM_ID = :ITEM_ID for update;

If your condition is met, you just update the table by rowid 如果满足您的条件,则只需按rowid更新表

update MY_TABLE
set ...
where rowid = :rowid

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM