Question
· Jan 14

INSERT OR UPDATE WITH A COUNTER

Hello,

So i want to use the INSERT OR UPDATE command so i can update a COUNTER for a given name:

 

INSERT OR UPDATE myTable
SET name='Omer',  counter = counter + 1;

 


as you can see with the above code - if the row is non-existent then we get an error because COUNTER is NULL! 
I tried the following to fix this but all have failed:

 


INSERT OR UPDATE myTable
SET name = 'Omer', 
    counter = CASE 
        WHEN counter IS NULL THEN 1 
        ELSE counter + 1
    END

 


INSERT OR UPDATE myTable SET name='Omer',counter = COALESCE(counter + 1, 1)

 

 

INSERT OR UPDATE myTable SET name='Omer',counter = IFNULL(counter + 1, 1)

For any of the solutions above i received the error:
 

  [SQLCODE: <-400>:<Fatal error occurred>]

  [%msg: <Unexpected error occurred: <UNDEFINED>%0Ao+3^%sqlcq.74.1 *sqldatad(3)>]

 

Side Note: Running the query below does work:

 

INSERT OR UPDATE myTable SET name='Omer',counter= 1

So this implies that problem is indeed with using the counter when it is NULL...

 

 

Would love to get some insight on that, Thx!

Product version: Caché 2018.1
Discussion (21)4
Log in or sign up to continue

The documentation link reports

https://docs.intersystems.com/hs20241/csp/docbook/DocBook.UI.Page.cls?KE...

When version checking is implemented, the property specified by VERSIONPROPERTY is automatically incremented each time an instance of the class is updated (either by objects or SQL). Prior to incrementing the property, InterSystems IRIS compares its in-memory value to its stored value. If they are different, then a concurrency conflict is indicated and an error is returned; if they are the same, then the property is incremented and saved.

I've used the VERSIONPROPERTY  parameter before and have observed that it is updated each time the object is saved.

I understand that you want to have full control of your version
Increment and Decrement eventually also more than just +1,-1
so VERSIONPROPERTY is a dead herring.
BUT: You can achieve this in combination with a little SQL method.

Property RowVer As %Integer [
   SqlComputeCode = { if $i({*},$g(%IncDec)) },
   SqlComputed,
   SqlComputeOnChange = (%%INSERT, %%UPDATE) ];
ClassMethod IncDec(step As %Integer = 0) As %Boolean [
      SqlName = IncDec, SqlProc ]
{
    set %IncDec=step quit 1
}

Now you can set the increment to any %Integer of your choice.
e.g.  -1 decrement by 1, 1 increment by 1,  0 leave it

How to use it:

INSERT OR UPDATE pck.myTable
    SET name='Omer'
    WHERE pck.IncDec(-2)=1
    AND .... any other conditions ....

the IncDec SQLmethod is used as a static method
it doesn't reference any row dependency
So it is executed once before any row related processing. 
if you omit it then row_version is not changed