I have a script for comparing the current value of a tag to the last value stored in the DB for that tag, and then storing the current value. Of course, this means I have to run a query to read the last value. The call looks like this:
lastDBvalue = system.db.runNamedQuery("Project", "Read_DB", {"tag_name" : PlcTag})
This query works, and calling it works, but how do I handle the situation where this is the first entry in the table for the tag? When the query times out, what is the value of lastDBvalue
?
Currently, this is how I have it written, but it doesn't seem to be working for the last 3 tags that I added.
#get latest DB info
lastDBvalue = system.db.runNamedQuery("Project", "Read_DB", {"tag_name" : PlcTag})
if ( not ((0 == lastDBvalue.rowCount))):
lastVal = lastDBvalue.getValueAt(0,'val')
lastTime = lastDBvalue.getValueAt(0,'t_stamp')
deltaT = system.date.secondsBetween(lastTime,system.date.now())
#large enough change in value to log the change, or minSample time is met
if ((0 == lastDBvalue.rowCount) or (abs(currentValue - lastVal) >= historicalDeadband) or ((minSampleRate > 0) and (deltaT >= minSampleRate))):
system.db.runNamedQuery("Project", "Store_Tag_Change", {"tag_name":PlcTag,"val":currentValue})
I might need to add a Try: Except:
, but haven't used that much so not sure where to put the Except:
Or maybe I need to edit my query:
SELECT TOP 1 val, t_stamp FROM Data where tag_id=:tag_name order by t_stamp desc
Trying to add IF EXISTS
before the select, I get SQLServerException: A result set was generated for update.
IF EXISTS (select 1 from Data Where tag_id = :tag_name)
SELECT TOP 1 val, t_stamp FROM Data where tag_id=:tag_name order by t_stamp desc