> ## Documentation Index
> Fetch the complete documentation index at: https://docs.coreflux.org/llms.txt
> Use this file to discover all available pages before exploring further.

# SQL Server Connector

> Store MQTT data in Microsoft SQL Server with automatic query execution and enterprise features

## SQL Server Overview

The `SQLSERVER` connector stores MQTT messages in Microsoft SQL Server databases. It supports Windows and SQL authentication, SSL connections, and enterprise features.

> [!NOTE]
>
> SQL Server is ideal for enterprise environments, especially those integrated with Microsoft ecosystems. It offers advanced features like Always On availability and native JSON support.

## Basic Syntax

```lot wrap theme={"theme":{"light":"css-variables","dark":"css-variables"},"languages":{"custom":["/languages/lot.json"]}}
DEFINE CONNECTOR SensorDB WITH TYPE SQLSERVER
    ADD SQL_CONFIG
        WITH SERVER "sqlserver.example.com"
        WITH PORT '1433'
        WITH DATABASE "IoTData"
        WITH USERNAME "iot_user"
        WITH PASSWORD "secure_password"
    ADD EVENT StoreSensorReading
        WITH SOURCE_TOPIC "sensors/+/reading"
        WITH QUERY "INSERT INTO Readings (RecordedAt, SensorId, Value) VALUES (GETDATE(), '{sensor_id}', '{value.json}')"
```

***

## Connection Configuration

### SQL\_CONFIG Parameters

**SERVER** `string` *required*

SQL Server hostname or IP address. Can include instance name (e.g., `server\instance`).

**DATABASE** `string` *required*

Target database name.

**USERNAME** `string` *required*

SQL Server username.

**PASSWORD** `string` *required*

SQL Server password.

> [accordion] Optional Settings
>
> **PORT** `integer`
>
> SQL Server port. Default: 1433.
>
> **USE\_SSL** `boolean`
>
> Enable SSL connection. Default: false.
>
> **TRUST\_SERVER\_CERTIFICATE** `boolean`
>
> Trust server certificate without validation. Default: false.

> [accordion] Pool and writes
>
> **MAX\_POOL\_SIZE** `integer`
>
> Maximum connections in the pool. Passed to the SQL Server driver. Omit to keep the driver default.
>
> **MIN\_POOL\_SIZE** `integer`
>
> Minimum connections in the pool. Passed to the SQL Server driver. Omit to keep the driver default. Must be less than or equal to `MAX_POOL_SIZE`.
>
> **CONNECTION\_IDLE\_LIFETIME** `integer`
>
> How long an idle pooled connection may be kept. Passed to the SQL Server driver. Omit to keep the driver default.
>
> **CONNECTION\_LIFETIME** `integer`
>
> How long a pooled connection may be kept. Passed to the SQL Server driver. Omit to keep the driver default.
>
> **WRITE\_CONCURRENCY** `integer`
>
> How many MQTT-triggered SQL events may run at once. Alias: `MAX_CONCURRENT_WRITES`. Optional.
>
> **WRITE\_QUEUE\_FULL\_POLICY** `string` (default: block)
>
> What to do when MQTT-triggered writes are already at `WRITE_CONCURRENCY`. `block` waits, and `WRITE_QUEUE_CAPACITY` is ignored. `drop_oldest` and `drop_newest` apply `WRITE_QUEUE_CAPACITY`. Dropping an event logs a Warning and counts the drop.
>
> **WRITE\_QUEUE\_CAPACITY** `integer`
>
> How many waiting MQTT-triggered events to keep when the policy is `drop_oldest` or `drop_newest`. Ignored when the policy is `block`.

Invalid pool values are refused. `MIN_POOL_SIZE` must be less than or equal to `MAX_POOL_SIZE`.

A failed query does not mark the connector Disconnected. A constraint violation, a cast error, a command timeout (`-2`), cannot-open-database (`4060`), an exhausted pool, and any other query failure leave it connected. Only a transport or connection failure marks it Disconnected, so one bad row does not stop later telemetry.

> [!WARNING]
>
> **Never hardcode credentials in production.** Use environment variables and encrypted secrets to keep sensitive values out of your connector definitions:
>
> ```lot wrap theme={"theme":{"light":"css-variables","dark":"css-variables"},"languages":{"custom":["/languages/lot.json"]}}
> WITH SERVER GET ENV "DB_HOST"
> WITH USERNAME GET ENV "DB_USER"
> WITH PASSWORD GET SECRET "DB_PASSWORD"
> ```
>
> See [Environment Variables & Secrets](https://docs.coreflux.org/latest/mqtt-broker/secrets-and-env.md) for setup and usage.

### Reconnecting after a dropped connection

When the database ends the connector's sessions or the connection drops, the connector is marked Disconnected. The next event reconnects it, straight away and then at most every 5 seconds until the database answers, and runs once the connection is back. No redeploy is needed. The event that was running on the dropped session fails and is not retried.

***

## Agent queries

An agent can read this database when the connector opts in and the agent grants `connector_query`. The agent runs one read statement. It cannot insert, update, or delete. See [Database queries](https://docs.coreflux.org/latest/lot-language/agents/syntax.md#database-queries).

| Clause | Default | Effect |
| - | - | - |
| `AGENT_QUERIES` | `"off"` | `"off"` or `"read"`. `"write"` is refused |
| `AGENT_USERNAME` / `AGENT_PASSWORD` | — | Login the agent uses. A separate read-only user is required |
| `AGENT_CONNECTION_STRING` | — | Alternative to the agent user and password |
| `AGENT_MAX_ROWS` | `200` | Most rows returned to the model |

SQL Server is refused unless you set `AGENT_USERNAME` and `AGENT_PASSWORD`, or `AGENT_CONNECTION_STRING`. It does not fall back to a read-only transaction on the connector login.

The person who asks and the agent's `DEFAULT_USER` both need `PublishSys` on `$SYS/Coreflux/Routes/<connector>/Query`.

```lot wrap theme={"theme":{"light":"css-variables","dark":"css-variables"},"languages":{"custom":["/languages/lot.json"]}}
DEFINE CONNECTOR PlantDB WITH TYPE SQLSERVER
    ADD SQL_CONFIG
        WITH SERVER GET ENV "SQLSERVER_HOST"
        WITH PORT 1433
        WITH DATABASE "plant"
        WITH USERNAME GET ENV "SQLSERVER_USER"
        WITH PASSWORD GET SECRET "SQLSERVER_PASSWORD"
        WITH AGENT_QUERIES "read"
        WITH AGENT_USERNAME GET ENV "SQLSERVER_AGENT_USER"
        WITH AGENT_PASSWORD GET SECRET "SQLSERVER_AGENT_PASSWORD"
        WITH AGENT_MAX_ROWS 200
```

***

## How placeholders are quoted

The broker places each placeholder in an event `QUERY` by the quotes around it. A publisher on the source topic can no longer change the SQL by putting SQL in the payload.

> [!WARNING]
>
> **Action:** Put every placeholder that carries text in single quotes (`WHERE status = '{payload}'`). Put a placeholder that names a table or column in double quotes (`FROM "{topic.2}"`) or brackets (`FROM [{topic.2}]`). An unquoted placeholder must be a number, a comma-separated list of numbers, `true`, `false`, or `null`. Anything else, including a bare name such as `line_1`, refuses the event. The message names the placeholder.

| Where the placeholder sits | What happens to the value |
| - | - |
| Inside single quotes: `'{payload}'` | Quotes in the value are doubled. |
| Inside double quotes: `"{topic.2}"` | Double quotes in the value are doubled. Use this for a table or column name. |
| Inside brackets: `[{topic.2}]` | The closing bracket is doubled. Use this for a table or column name. |
| Unquoted: `VALUES ({value})` | Only a number, a comma-separated list of numbers, `true`, `false`, or `null`. |
| In a SQL comment | Left as written. |

`{env.NAME}` and `{secret.NAME}` are placed as written. A value that itself contains `{topic}` is stored as text and is not expanded again. The same rules on the other SQL engines are in [How placeholders are quoted](https://docs.coreflux.org/latest/connectors/data-storage/overview#how-placeholders-are-quoted). MongoDB and OpenSearch JSON queries place each value as one JSON value instead (see [OpenSearch placeholders](https://docs.coreflux.org/latest/connectors/data-storage/opensearch.md#placeholders)).

***

## Writing Data

> [tab] Basic Storage
>
> Store sensor data in SQL Server:
>
> ```lot wrap theme={"theme":{"light":"css-variables","dark":"css-variables"},"languages":{"custom":["/languages/lot.json"]}}
> DEFINE CONNECTOR SensorStorage WITH TYPE SQLSERVER
>     ADD SQL_CONFIG
>         WITH SERVER "sqlserver.example.com"
>         WITH PORT '1433'
>         WITH DATABASE "IoTData"
>         WITH USERNAME "iot_user"
>         WITH PASSWORD "secure_password"
>     ADD EVENT StoreReading
>         WITH SOURCE_TOPIC "sensors/+/reading"
>         WITH QUERY "INSERT INTO SensorReadings (Timestamp, SensorId, Value) VALUES (GETDATE(), '{sensor_id}', '{value.json}')"
> ```

> [tab] With SSL
>
> Secure connection with trusted certificate:
>
> ```lot wrap theme={"theme":{"light":"css-variables","dark":"css-variables"},"languages":{"custom":["/languages/lot.json"]}}
> DEFINE CONNECTOR SecureStorage WITH TYPE SQLSERVER
>     ADD SQL_CONFIG
>         WITH SERVER "sqlserver.cloud.com"
>         WITH PORT '1433'
>         WITH DATABASE "Production"
>         WITH USERNAME "app_user"
>         WITH PASSWORD "secure_password"
>         WITH USE_SSL "true"
>         WITH TRUST_SERVER_CERTIFICATE "true"
>     ADD EVENT StoreEvent
>         WITH SOURCE_TOPIC "events/#"
>         WITH QUERY "INSERT INTO Events (Timestamp, Topic, Payload) VALUES (GETDATE(), '{source_topic}', '{value.json}')"
> ```

> [tab] Named Instance
>
> Connect to a named SQL Server instance:
>
> ```lot wrap theme={"theme":{"light":"css-variables","dark":"css-variables"},"languages":{"custom":["/languages/lot.json"]}}
> DEFINE CONNECTOR InstanceStorage WITH TYPE SQLSERVER
>     ADD SQL_CONFIG
>         WITH SERVER "server.example.com\\MSSQLSERVER"
>         WITH DATABASE "IoTData"
>         WITH USERNAME "iot_user"
>         WITH PASSWORD "secure_password"
>     ADD EVENT StoreData
>         WITH SOURCE_TOPIC "data/#"
>         WITH QUERY "INSERT INTO DataLog (Timestamp, Topic, Data) VALUES (GETDATE(), '{source_topic}', '{value.json}')"
> ```

> [tab] UPSERT
>
> SQL Server uses the `MERGE` statement for upsert logic — insert a row if it doesn't exist, update it if it does:
>
> ```lot wrap theme={"theme":{"light":"css-variables","dark":"css-variables"},"languages":{"custom":["/languages/lot.json"]}}
> DEFINE CONNECTOR DeviceRegistry WITH TYPE SQLSERVER
>     ADD SQL_CONFIG
>         WITH SERVER "sqlserver.example.com"
>         WITH PORT '1433'
>         WITH DATABASE "IoTData"
>         WITH USERNAME "iot_user"
>         WITH PASSWORD "secure_password"
>     ADD EVENT RegisterDevice
>         WITH SOURCE_TOPIC "devices/+/registered"
>         WITH QUERY "MERGE Devices AS target USING (SELECT '{value.json.device_id}' AS device_id, '{value.json.name}' AS name, '{value.json.area}' AS area) AS source ON (target.DeviceId = source.device_id) WHEN MATCHED THEN UPDATE SET Name = source.name, Area = source.area, UpdatedAt = GETDATE() WHEN NOT MATCHED THEN INSERT (DeviceId, Name, Area, Active, UpdatedAt) VALUES (source.device_id, source.name, source.area, 1, GETDATE());"
> ```

> [tab] UPDATE
>
> Modify existing records when a status change arrives:
>
> ```lot wrap theme={"theme":{"light":"css-variables","dark":"css-variables"},"languages":{"custom":["/languages/lot.json"]}}
> DEFINE CONNECTOR DeviceRegistry WITH TYPE SQLSERVER
>     ADD SQL_CONFIG
>         WITH SERVER "sqlserver.example.com"
>         WITH PORT '1433'
>         WITH DATABASE "IoTData"
>         WITH USERNAME "iot_user"
>         WITH PASSWORD "secure_password"
>     ADD EVENT UpdateDeviceStatus
>         WITH SOURCE_TOPIC "devices/+/status"
>         WITH QUERY "UPDATE Devices SET CurrentStatus = '{value.json.status}', LastSeen = GETDATE() WHERE DeviceId = '{value.json.device_id}'"
> ```

> [tab] DELETE
>
> Remove records on a decommission or cleanup event:
>
> ```lot wrap theme={"theme":{"light":"css-variables","dark":"css-variables"},"languages":{"custom":["/languages/lot.json"]}}
> DEFINE CONNECTOR DeviceRegistry WITH TYPE SQLSERVER
>     ADD SQL_CONFIG
>         WITH SERVER "sqlserver.example.com"
>         WITH PORT '1433'
>         WITH DATABASE "IoTData"
>         WITH USERNAME "iot_user"
>         WITH PASSWORD "secure_password"
>     ADD EVENT DecommissionDevice
>         WITH SOURCE_TOPIC "devices/+/decommissioned"
>         WITH QUERY "DELETE FROM Devices WHERE DeviceId = '{value.json.device_id}' AND Active = 0"
> ```

> [!NOTE]
>
> **Alternative: STORE IN with Models** — Instead of writing EVENT queries, you can bind a [model](https://docs.coreflux.org/latest/lot-language/models/overview) directly to this connector. Every `PUBLISH MODEL` call automatically inserts a row — no query needed:
>
> ```lot wrap theme={"theme":{"light":"css-variables","dark":"css-variables"},"languages":{"custom":["/languages/lot.json"]}}
> DEFINE MODEL SensorReading
>     ADD STRING "sensor_id"
>     ADD DOUBLE "value"
>     STORE IN "SensorStorage"
>         WITH TABLE "SensorReadings"
> ```
>
> See [Data Storage Overview](https://docs.coreflux.org/latest/connectors/data-storage/overview#with-models-store-in) for the full STORE IN workflow.

***

## Reading Data

EVENTs also support SELECT queries to read data back from the database. Publish a message to the event's `SOURCE_TOPIC`, and the query result is published to `DESTINATION_TOPIC`:

```lot wrap theme={"theme":{"light":"css-variables","dark":"css-variables"},"languages":{"custom":["/languages/lot.json"]}}
DEFINE CONNECTOR SensorDB WITH TYPE SQLSERVER
    ADD SQL_CONFIG
        WITH SERVER "sqlserver.example.com"
        WITH PORT '1433'
        WITH DATABASE "IoTData"
        WITH USERNAME "iot_user"
        WITH PASSWORD "secure_password"
    ADD EVENT GetLatestReading
        WITH SOURCE_TOPIC "db/query/latest"
        WITH DESTINATION_TOPIC "db/result/latest"
        WITH QUERY "SELECT TOP 1 SensorId, Value FROM Readings WHERE SensorId = '{payload}' ORDER BY RecordedAt DESC"
```

To trigger this query, publish the sensor ID to the source topic:

```
Topic:   db/query/latest
Payload: temp001
```

The query result is published to `db/result/latest`, where your actions or external clients can consume it.

### Timed Polling

EVENTs can also run SELECT queries on a fixed schedule using `WITH EVERY`:

```lot wrap theme={"theme":{"light":"css-variables","dark":"css-variables"},"languages":{"custom":["/languages/lot.json"]}}
DEFINE CONNECTOR DeviceRegistry WITH TYPE SQLSERVER
    ADD SQL_CONFIG
        WITH SERVER "sqlserver.example.com"
        WITH PORT '1433'
        WITH DATABASE "IoTData"
        WITH USERNAME "iot_user"
        WITH PASSWORD "secure_password"
    ADD EVENT PollActiveDevices
        WITH EVERY 10 SECONDS
        WITH DESTINATION_TOPIC "dashboard/devices/active"
        WITH QUERY "SELECT DeviceId, Name, CurrentStatus, LastSeen FROM Devices WHERE Active = 1 ORDER BY Name"
```

***

## Table Schema Examples

```sql wrap theme={"theme":{"light":"css-variables","dark":"css-variables"},"languages":{"custom":["/languages/lot.json"]}}
-- Basic sensor readings
CREATE TABLE SensorReadings (
    Id INT IDENTITY(1,1) PRIMARY KEY,
    Timestamp DATETIME2 DEFAULT GETDATE(),
    SensorId NVARCHAR(50),
    Value FLOAT
);

-- JSON storage (SQL Server 2016+)
CREATE TABLE Events (
    Id INT IDENTITY(1,1) PRIMARY KEY,
    Timestamp DATETIME2 DEFAULT GETDATE(),
    Topic NVARCHAR(255),
    Payload NVARCHAR(MAX)
);
```

***

## Troubleshooting

> [accordion] Connection Refused
>
> * Verify SERVER and PORT are correct
> * Check SQL Server is running and accepting TCP connections
> * Enable TCP/IP in SQL Server Configuration Manager
> * Verify firewall allows connections on port 1433

> [accordion] Authentication Failed
>
> * Verify USERNAME and PASSWORD are correct
> * Ensure SQL Server authentication is enabled (mixed mode)
> * Check user has permissions on the DATABASE

> [accordion] SSL/Certificate Errors
>
> * Set TRUST\_SERVER\_CERTIFICATE "true" for self-signed certs
> * Verify SSL is configured on SQL Server

> [accordion] Never Connects: Globalization Invariant Mode or SQL Server Connector Unavailable
>
> The broker runs without the ICU library, which SQL Server connections need. This happens on broker 2.22 and earlier, or when `DOTNET_SYSTEM_GLOBALIZATION_INVARIANT=1` is set.
>
> * Upgrade the broker
> * Remove `DOTNET_SYSTEM_GLOBALIZATION_INVARIANT` from the broker's environment
> * On a portable Linux binary, install `libicu` on the host. See [Installation](https://docs.coreflux.org/latest/quick-start/installation.md)

***

## Next Steps

> [card] [Data Storage Connectors Overview](https://docs.coreflux.org/latest/connectors/data-storage/overview)
>
> Compare all storage options.

> [card] [MongoDB Connector](https://docs.coreflux.org/latest/connectors/data-storage/mongodb.md)
>
> Configure MongoDB document storage.


This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.