LabVIEW has several ways to reach SQL Server, and they differ less in what they can write than in how they fail. A direct ADO connection inside the test application is quick to build and hard to operate at scale. A small service layer costs more up front and gives every station one place to validate, retry, and reconcile. The right choice depends on the number of stations, the criticality of the record, and who supports the system after the original developer leaves.
Four ways to write the data
| Option | How it works | Best for | Main risk |
|---|---|---|---|
| Direct ADO / database toolkit | LabVIEW opens a connection and executes SQL | One station, stable schema, simple record | Connection handling, credentials, and business rules spread across stations |
| .NET assembly call | LabVIEW calls a .NET library that owns the data access | A team already using .NET; shared connection logic | Deployment of the assembly and its dependencies on every station |
| REST service | The station posts JSON to an internal API | Multiple stations, central validation, ERP integration | Network dependency and service availability; needs a local retry path |
| File drop | The station writes a file; another process imports it | A legacy system with no other interface | No transaction boundary, partial files, duplicate imports |
A schema that holds up
Separate the test header from its individual measurements. A test can produce one value or twenty; a single wide table either wastes columns or runs out of them. The header carries the production identity and the overall status; the measurement rows carry the values and limits.
CREATE TABLE dbo.TestResult (
ResultId uniqueidentifier NOT NULL PRIMARY KEY,
StationId nvarchar(32) NOT NULL,
JobId nvarchar(32) NOT NULL,
BatchId nvarchar(32) NULL,
SampleId nvarchar(32) NOT NULL,
MethodId nvarchar(32) NOT NULL,
OperatorId nvarchar(64) NOT NULL,
MeasuredAtUtc datetime2(3) NOT NULL,
ResultStatus tinyint NOT NULL, -- 1 pass, 2 fail, 3 invalid
IdempotencyKey char(64) NOT NULL,
CONSTRAINT UQ_TestResult_Key UNIQUE (IdempotencyKey)
);
CREATE TABLE dbo.TestMeasurement (
MeasurementId uniqueidentifier NOT NULL PRIMARY KEY,
ResultId uniqueidentifier NOT NULL
REFERENCES dbo.TestResult(ResultId),
Name nvarchar(64) NOT NULL,
NumericValue decimal(18,6) NULL,
Unit nvarchar(16) NOT NULL,
LowerLimit decimal(18,6) NULL,
UpperLimit decimal(18,6) NULL,
QualityStatus tinyint NOT NULL
);
CREATE INDEX IX_TestResult_Job
ON dbo.TestResult (JobId, MeasuredAtUtc);
Illustrative schema. Add calibration, instrument status, method revision, and an audit table as the quality system requires.
The insert path
Use one transaction for the header and its measurement rows. Either the whole result is recorded or none of it is. Use parameterized commands, not string concatenation; a measurement application that builds SQL from operator input is an injection path and a quoting bug waiting to happen.
BEGIN TRANSACTION;
INSERT INTO dbo.TestResult
(ResultId, StationId, JobId, SampleId, MethodId, OperatorId,
MeasuredAtUtc, ResultStatus, IdempotencyKey)
VALUES
(@ResultId, @StationId, @JobId, @SampleId, @MethodId, @OperatorId,
@MeasuredAtUtc, @ResultStatus, @IdempotencyKey);
INSERT INTO dbo.TestMeasurement
(MeasurementId, ResultId, Name, NumericValue, Unit,
LowerLimit, UpperLimit, QualityStatus)
VALUES
(@MeasurementId1, @ResultId, @Name1, @Value1, @Unit1,
@Lower1, @Upper1, @Quality1),
(@MeasurementId2, @ResultId, @Name2, @Value2, @Unit2,
@Lower2, @Upper2, @Quality2);
COMMIT TRANSACTION;
Illustrative transaction with two measurement rows. A real implementation adds error handling and a rollback path.
Keep the transaction short. Do not hold it open while the operator types a comment or confirms a dialog. Collect the data first, then open, insert, and commit.
Idempotency: the retry that does not duplicate
A timeout does not mean the insert failed. The database may have committed the row and lost the acknowledgement. If the application retries blindly, the result is stored twice. The fix is a unique key that represents the business event, enforced by the database.
A practical key is a hash of the fields that identify the measurement: station, job,
sample, method, and measurement time to the millisecond, plus a sequence number if the same
sample can legitimately be measured twice at the same timestamp. Compute the hash in the
application, store it in a char(64) column, and add a unique constraint.
On a duplicate-key error, treat the insert as already successful — but only after confirming that the existing row matches the payload. A key collision with different values is a bug, not a duplicate.
Connections, timeouts, and retries
- Open late, close early. A connection held open while an operator runs a ten-minute test is a connection the database cannot use for anything else.
- Use pooling where the stack supports it. A .NET data layer gets connection pooling; a direct LabVIEW implementation may not. Repeated connect/disconnect has a cost, but a leaked connection is worse.
- Set a command timeout. The default may be too long for an operator screen or too short for a large batch insert. Choose a value and handle the timeout explicitly.
- Retry only transient failures. A deadlock, a connection failure, or a timeout may succeed on retry. A constraint violation or a permission error will not. Retrying the second class hides the real problem.
- Back off. Retry with increasing delay and jitter. A tight retry loop against an unavailable server makes the outage worse.
- Limit attempts. After a defined number, write the record to a local durable store and surface the failure. Do not discard it.
Timestamps and units
Use datetime2(3) for measurement time. The older datetime type
rounds to increments of about 3.33 ms, which is unnecessary ambiguity for a test record.
Store UTC. Convert to plant-local time in the report, using a configured time zone rather
than the server's regional setting.
Record the measurement time and the insert time separately. The difference is a useful health signal: a station whose inserts routinely arrive minutes after the measurement has a network or queue problem. It is also the evidence you need when someone asks whether a result was recorded at the time of the test.
Store the unit with every value. A column called Density does not tell a later
reader whether the value is g/cm³, kg/m³, or a percentage of theoretical. If the application
converts, store the original value and unit as well as the converted one.
Offline behavior: decide before the first outage
A test station on a plant network will lose the database at some point. The design needs a defined behavior, not an unhandled error dialog.
| Strategy | Behavior | Suitable when |
|---|---|---|
| Block the test | No result is accepted without a database write | The record is mandatory and production can pause |
| Local queue | Result is stored locally and posted when the database returns | Production must continue; a short delay is acceptable |
| Local record, unsynchronized | Result is stored locally and marked as not yet synchronized | The local record is the operational truth for a period |
| Retry only | The application holds the result in memory and retries | Never for a quality record; a restart loses the data |
A local queue needs the same idempotency key as the direct path, or replay will duplicate. It also needs a bounded size and a visible status. A queue that has been silently growing for three weeks is not an offline strategy; it is an outage that has not been noticed.
Validation checklist
- Insert a normal result and confirm the header and measurement rows are committed together.
- Repeat the same submission and confirm the unique key prevents a second record.
- Stop SQL Server mid-transaction and confirm the application neither reports success nor loses the result.
- Introduce a command timeout after the server has committed, then retry, and confirm idempotency holds.
- Submit an invalid job or sample identifier and confirm the result is rejected or quarantined with a reason.
- Change the station clock and confirm UTC storage and the ingest-time difference behave as designed.
- Run the largest expected batch and confirm the transaction completes within the timeout.
- Run two stations at once and confirm the schema and keys do not collide.
- Check the application account's permissions: insert and execute only, no schema changes.
- Restart the station with a queued result and confirm replay completes exactly once.
Security for a test-station account
- Least privilege. The application account needs INSERT on its tables and EXECUTE on its procedures. It does not need db_owner, sysadmin, or rights to other databases.
- No shared credentials. A station-specific account makes the audit trail meaningful and lets an account be disabled without stopping the plant.
- Protect the connection string. Use Windows authentication where possible, or a protected configuration store. Do not leave a password in a text file on the station.
- Encrypt the connection. SQL Server supports encrypted connections; use a trusted certificate rather than disabling validation to make it work.
- Do not log sensitive values. The diagnostics log should not contain credentials, and it should be protected like the measurement data.
When to add a service layer
A direct insert is a reasonable first design for one station and one table. A service layer starts to earn its cost when:
- Several stations write the same record shape, and the validation rules must not drift.
- The measurement must be posted to an ERP, MES, or QMS through a supported API.
- The record needs an audit trail, an approval step, or a correction workflow.
- The database is remote or intermittently connected, and a durable queue is required.
- The application must keep working while the database schema changes behind it.
The service layer does not have to be large. A focused .NET API with a database and a queue is often enough. The point is to put the business rules and the failure handling in one place rather than in every station's block diagram.
LabVIEW development and test automation covers the measurement application, instrument integration, scaling, calibration checks, and the production identity that this record depends on.