Select with SQL and write to PLC Tag

Hello Forum, I am having issues figuring out how to get this code to work. I’m looking in a table that is a schedule of events and I want to check based on the current time what type of event is scheduled. So based on the schedule I want to write what type of event is going on to a tag in the PLC. Right now this code is running without errors but my tag isn’t changing. Do you know why this wouldn’t work?

CurrentTime = system.date.now()
CurrentTime = str(system.date.format(CurrentTime, "yyyy-MM-dd HH:mm:ss"))
query = "SELECT EventType FROM Table WHERE CellLabel = ? AND StartTime < ? AND EndTime > ?"
args = ["CellLabel", CurrentTime , CurrentTime]
CellStatus = system.db.runPrepQuery(query, args)

if CellStatus == "Break":
	system.tag.write("Cell/Program: Ignition/BREAK_TIME_ACTIVE", 1)
if CellStatus != "Break":
	system.tag.write("Cell/Program: Ignition/BREAK_TIME_ACTIVE", 0)

runPrepQuery should be returning a dataset, not a string, so your first write should never be hit.

Not sure what the def of P375LowerStatus is, so no idea if that write gets hit.

One good way to debug things like this is to add a few print lines into your code so you can see what lines are getting hit and what data is coming back.

As @KathyApplebaum says runPreqQuery returns a dataset.

If the expectation is that your query will return 1 result row then you should use runScalarPrepQuery which will return a scalar value.

Your script would then look a little something like this:

CurrentTime = system.date.format(system.date.now(),"yyyy-MM-dd HH:mm:ss")
query = "SELECT EventType FROM Table WHERE CellLabel = ? AND StartTime < ? AND EndTime > ?"
args = ["CellLabel", CurrentTime , CurrentTime]
CellStatus = system.db.runScalarPrepQuery(query,args)

system.tag.write("Cell/Program: Ignition/BREAK_TIME_ACTIVE",CellStatus == "Break")
1 Like