How-to
Why end-of-day totals belong in a SQL row not the tag historian
Short answer
No second tag set is needed. Keep the live tags bound to the marquee and have the push button call one script library function that checks tag quality and inserts the three values as one timestamped row in a SQL table with system.db.runPrepUpdate or a named query, with a unique date key so a second press cannot duplicate the day's record.
On this page
- Do I need two tags, one for live values and one for history?
- What table should the daily totals land in?
- How do I write the insert once and call it from anywhere?
- How does the push button call the script?
- How do I stop a double press or a midnight reset from corrupting the record?
- How do I prove the stored row matches the marquee?
- When is the tag historian still the right choice?
- Questions asked
A push button should write one timestamped row to a SQL table, and no second set of tags is needed. Leave the live tags bound to the marquee; the button calls one script library function that reads the tag paths, checks tag quality and inserts the values with system.db.runPrepUpdate or a named query. The tag historian stores on-change signal data: each tag becomes its own stream with its own timestamp, and a total that repeats from one day to the next can produce no new stored point at all. A daily total is a record, not a signal. Build it in this order:
- Create the totals table with a unique date key.
- Write the insert as a library function with a quality check.
- Call it from the button's press event.
- Prove the row against the marquee, then force bad quality and confirm nothing stores.
Do I need two tags, one for live values and one for history? #
No, one set of live tags covers the marquee: the button writes one row holding all three values under a single timestamp, while historized snapshot copies would split each day into three streams — about 1,095 stored points for three values over a year, against 365 rows in one table.
Tag history writes a stored point when a tag's value changes, filtered by the tag's value mode and deadband, and it never stores a second point for a value that did not move. The live tags therefore keep no History Enabled property in the Tag Editor: nothing about their configuration changes. Query the history back at a day boundary and you get the stored point nearest it or an interpolation, not the snapshot the operator approved.
| Design | What gets stored | What you get back later |
|---|---|---|
| Historized snapshot tags | One history stream per tag, one timestamp per stream | A join across three streams to rebuild the day |
| One SQL row | All of the day's values on one row, one timestamp | A table or XY plot with no joins |
The arithmetic is the argument: three snapshot tags over a year is 3 × 365 = 1,095 history points scattered across three streams, against 365 rows in one table that a plain SELECT reads. What gets stored when a value barely moves is its own subject; see why the Auto deadband style delays tag history storage.
What table should the daily totals land in? #
Create one table with a timestamp, a date key under a unique constraint, and one column per marquee value: for example daily_production with t_stamp, shift_date, faults, rejects and avg_cycle_time, where shift_date is the column that blocks a second insert for the same day.
Type names differ by engine: DATETIME fits SQL Server and MySQL, TIMESTAMP fits PostgreSQL, so adapt the statement to the database you run. Add the columns you will want within the year — line ID, shift, production count — now rather than in a migration later.
CREATE TABLE daily_production (
t_stamp DATETIME NOT NULL,
shift_date DATE NOT NULL,
faults INT,
rejects INT,
avg_cycle_time FLOAT,
CONSTRAINT uq_daily_production_day UNIQUE (shift_date)
);
Check the table before writing any script: run SELECT * FROM daily_production in the Database Query Browser. An empty result with the five column headers proves the table exists and the connection reaches it. Note the exact connection name the Gateway configuration shows, because the script addresses the connection by that name.
How do I write the insert once and call it from anywhere? #
Write the insert once as a project library function that any screen, button or timer script can call: it reads the tag paths, refuses to store anything when a value has bad quality, and runs system.db.runPrepUpdate with a parameterized INSERT that returns the number of rows affected.
# Project library script, module name for example "production"
DB = "MES-Reporting" # example connection name; use the exact name your Gateway shows
PATHS = [
"[default]Line1/Faults",
"[default]Line1/Rejects",
"[default]Line1/AvgCycleTime",
] # example paths; use the tags the marquee is bound to
def snapshot():
values = system.tag.readBlocking(PATHS)
if not all(v.quality.isGood() for v in values):
return False
sql = ("INSERT INTO daily_production "
"(t_stamp, shift_date, faults, rejects, avg_cycle_time) "
"VALUES (?, ?, ?, ?, ?)")
now = system.date.now()
args = [now, system.date.format(now, "yyyy-MM-dd")]
args += [v.value for v in values]
return system.db.runPrepUpdate(sql, args, DB) == 1
The quality test separates a tag fault from a script fault: when a path has bad quality, the function writes nothing and returns False, so a stale zero never becomes the day's total. system.db.runPrepUpdate runs the prepared statement and returns the number of rows affected, so comparing to 1 confirms exactly one insert.
A named query does the same job and keeps the SQL out of the script text: store the INSERT as a named query and call it from the function with system.db.runNamedQuery and the same five arguments. The SQL Bridge module adds a separate configuration model and solves nothing for one on-demand insert.
Test the function before wiring anything: run print(production.snapshot()) in the Script Console. It must print True, and the SELECT from the table step must show one row. Delete that test row afterward.
How does the push button call the script? #
Call the library function from the button's press event and treat its False return as an operator-facing failure: the handler is one guard clause that shows a message when the snapshot is not saved and stays silent when the row is in.
In a Vision window the event is the button's actionPerformed script; in a Perspective view it is the component's onActionPerformed script. The body is the same in both:
if not production.snapshot():
system.gui.messageBox("Snapshot not saved: a source tag has bad quality")
system.gui.messageBox is a Vision call. In Perspective, surface the same failure with a popup message or a status label bound to the function's return value.
| What you see | Cause | Where to look |
|---|---|---|
| Button does nothing, no error | Event not wired, or a name error inside the library | Script console output and the logs for the press event |
| Snapshot not saved message | One source tag has bad quality | The quality column on each path in PATHS |
| Traceback on the insert | Wrong connection name, or columns that do not match the table | The DB name against the connection, INSERT columns against CREATE TABLE |
| Row written with stale or zero values | PATHS points at different tags than the marquee bindings |
Compare the marquee bindings with PATHS |
Press the button once with the marquee showing known values; one new row must appear.
How do I stop a double press or a midnight reset from corrupting the record? #
Put a unique constraint on the date column and let the database refuse the second insert, then fix the reset order: the button must run before the PLC zeroes the daily counters, because a press after the reset stores zeros with good quality and no check catches it.
The UNIQUE constraint turns a double press into a refused insert: the second call raises an error instead of writing a twin row. Wrap the call in a try/except that maps that failure to a totals-already-saved message, or run a quick SELECT for today's shift_date inside snapshot() before inserting. Either guard satisfies the acceptance test below.
Reset order is the failure no database guard catches. If the PLC zeroes the daily counters at rollover, a press after the reset stores zeros with good quality. Gate the button with a PLC day-closed bit, move the trigger into the PLC reset logic, or call snapshot() from a Gateway timer script timed before the reset — the function runs unchanged.
How do I prove the stored row matches the marquee? #
Prove the row with one comparison and one failure test: the newest row must carry the same three numbers the marquee showed at the press, and a forced bad-quality tag must leave the table with no new row and the message on screen.
Run this acceptance sequence once at commissioning and again after any change to the paths:
- Note the marquee while the line runs: for example 14 faults, 23 rejects, average cycle time 41.6 s.
- Press the button once, then run
SELECT TOP 1 * FROM daily_production ORDER BY t_stamp DESCin the Database Query Browser; use theLIMIT 1form on engines without TOP. - Compare the columns with the noted numbers: the row must read 14, 23, 41.6, allowing only for real changes between the note and the press.
- Bind a table component to the same query, and bind an XY chart of t_stamp against a value column for day-over-day review.
- Force bad quality in a test environment, for example by stopping the driver connection, and press the button: no new row, and the failure message appears.
Step 3 is the whole proof: one press, one row, the marquee's numbers under one timestamp.
When is the tag historian still the right choice? #
Keep the historian for dense signal data and the SQL row for records: faults, rejects and cycle time sampled continuously across the shift are signal data for the tag historian, while the end-of-day result is one record, and each belongs where its shape fits.
The historian earns its place on dense data: on-change and deadband-filtered points, one-second samples, the signals a trend needs. The two storage models differ enough that the choice is worth reading in full; see the tradeoffs between Ignition Tag Historian and SQL Bridge storage for a short-term trend database. Retention sizing then covers the trend data alone; see how to estimate historian disk space from measured daily growth, because the daily totals row lives outside that sizing entirely.
Decision, in three lines: keep the live tags bound to the marquee exactly as they are; the end-of-day numbers go through the button into one quality-checked SQL row guarded by the date key; anything that needs a trend across the shift stays in the tag historian.
Questions asked
What happens if the database connection is down when the operator presses the button?
The insert call fails with an error instead of writing a partial row. Catch it in the button handler, show the operator a message that the totals were not saved, and let them press again once the connection is healthy. The marquee keeps showing live values the whole time, so nothing is lost in the shift.
Do I need to change anything on Ignition 8.3?
No. system.db.runPrepUpdate stays the insert path, and named queries behave the same; the older runQuery call is deprecated for writes on 8.3, so keep inserts on the prepared-update function. The tag read and the unique key on the date column are unchanged between the versions.
Can several lines share one daily totals table?
Yes. Add a line_id column now, include it with shift_date in the same unique constraint, and pass the line identifier as one more script argument. Each line then gets exactly one row of its own per day, and a query for one line filters on line_id without touching the other rows.
Can the snapshot run on a schedule instead of waiting for the button?
Yes. The same library function runs unchanged from a Gateway timer script at the rollover time you choose. Keep the quality check and the unique date key, because a scheduled run plus a manual press on the same day then cannot double the row, and a timer that fires before the counter reset still stores the full day.