---
title: Monitor SQL Server with Custom TSQL Scripts and Remote Actions in Nodinite
description: Unlock advanced SQL Server monitoring with Nodinite. Create custom TSQL scripts for proactive alerts, automate management, and empower self-service actions for your business.
---

# <i class="fal fa-database" aria-hidden="true"></i> Managing TSQL Monitoring Statements

Gain full control over your SQL Server monitoring with the <span class="nodinite-product-name" title="The node that unites different systems. Or as we call it Nodinite">Nodinite</span> [Database Monitoring Agent][]. This page shows you how to leverage custom TSQL scripts for proactive monitoring, instant alerts, and self-service management—empowering both integration experts and business users.

✅ Monitor SQL Server health and business data using your own TSQL logic  
✅ Instantly receive alerts and automate remediation with [Remote Actions][]  
✅ Empower self-service for business [users][Users] to execute pre-defined scripts  
✅ Centralize monitoring and management for all your SQL Server resources  

![A SQL Statement in Error with its THROW message as Log Text, then Show Action Scripts runs a script and shows its result set, animated walkthrough (7.12)][16]  
*Animated walkthrough: the statement 'Contoso: Orders awaiting confirmation' is **Error**, and its THROW message is the Log Text. **Details**, then **Show Action Scripts**: **Execute** 'Show the orders awaiting confirmation', confirm, and read the seven orders in the result.*  

>Automate your database monitoring and get alerts using your custom coded TSQL statements! Gain actionable insights and perform administrative tasks by executing pre-defined TSQL scripts—all from a single platform.

The <span class="nodinite-product-name" title="The node that unites different systems. Or as we call it Nodinite">Nodinite</span> Database Monitoring Agent provides two major features for SQL Server:

1. <i class="fal fa-traffic-light-stop" aria-hidden="true"></i> **Monitoring** – Get alerts from logic in custom-built TSQL statements
2. <i class="fal fa-wrench" aria-hidden="true"></i> **Management** – Allow end-users to execute pre-defined TSQL statements from one or more TSQL Script collections  

<div class="mermaid">
graph TD
   subgraph "fal:fa-traffic-light-stop Monitoring"
      roAH(fal:fa-code Text/AdHoc)
      roSP(fal:fa-function Stored Procedures)
   end
   subgraph "fal:fa-wrench Management"
      ro1(fal:fa-boxes Execute TSQL Scripts on demand)
   end
</div>

*Here's a visual overview of how monitoring and management features are organized in Nodinite.*

To use the Monitoring feature, provide either **Stored Procedures** or **Text/AdHoc** TSQL statements. Implement your business logic using the examples on this page.

* **Text/AdHoc**
* **Stored Procedures**

<sup><span class="nodinite-new-badge">New 7.13</span></sup>  
A **SQL Statement** in the <span class="nodinite-product-name" title="The node that unites different systems. Or as we call it Nodinite">Nodinite</span> [Database Monitoring Agent][Database Monitoring Agent] is a group: one authentication (the connection string, and optionally impersonation) and a list of **monitoring statements**. Each enabled monitoring statement of an enabled SQL Statement is one [Resource][Resources] to manage, named after the monitoring statement's **Display Name**; the SQL Statement itself is not a Resource. Assign these [Resources][] to one or more [Monitor Views][] to trigger alerts according to the evaluated monitor state. Use the <span class="nodinite-product-name" title="The node that unites different systems. Or as we call it Nodinite">Nodinite</span> [Alarm Plugins][] to push alerts.  

<i class="fal fa-folder" aria-hidden="true"></i> In the [Monitor Views][], the monitoring statements of [Microsoft SQL Server][SQL Server Options] share the **SQL Statements** [Category][Categories], and their **Application** is the name of the SQL Server configuration.  
![A Monitor View with two monitoring statements, Contoso Failed Orders and Contoso Open Orders, both OK in the SQL Statements Category, each with its own Log Text (7.13)][0]  
*Two monitoring statements of one SQL Statement, each its own Resource with its own Log Text: *Failed orders: 0* and *Open orders: 3*.*  

<div class="mermaid">
graph LR
   subgraph "Configuration"
      c["fal:fa-code 1 SQL Statement"] --> m1["fal:fa-traffic-light Monitoring statement 1"]
      c --> m2["fal:fa-traffic-light Monitoring statement 2"]
   end
   m1 --> r1[fal:fa-lightbulb-on Resource 1]
   m2 --> r2[fal:fa-lightbulb-on Resource 2]
</div>

*One SQL Statement holds the connection for any number of monitoring statements; each enabled monitoring statement is one [Resource][Resources] to monitor.*

## <i class="fal fa-key" aria-hidden="true"></i> What are the key features for Monitoring SQL Statements?

* **State Evaluation** – Monitor and evaluate the state based on your custom TSQL logic. See the TSQL/Stored procedure code examples further down in this guide.  
* **Actions** – Support for the execution of [Remote Actions][]

### How do SQL Statements evaluate?

The following monitoring states exist:

|State|Status|Description|<i class="fal fa-bolt" aria-hidden="true"></i> Actions|  
|---|---|---|---|  
|🚫 <span title="Used to indicate an error/fatal condition">Unavailable</span>|**Resource not available**|Evaluation of the 'SQL Statement' is not possible either due to network or security-related problems|Review the [prerequisites][Prerequisites for Database Monitoring Agent]|  
|❌ <span title="Used to indicate that an error or abnormal condition has been detected">Error</span>|**Error state raised**|The SQL Statement is raising an exception to report that one or more major problems/errors exist|<i class="fal fa-edit" aria-hidden="true"></i> [Edit](#fa-traffic-light-monitoring-statement-tab)|  
|⚠️ <span title="Used to indicate an unexpected but not invalid state">Warning</span>|**Warning state raised**|The SQL Statement is raising a warning to report that one or more minor problems/errors exist|<i class="fal fa-edit" aria-hidden="true"></i> [Edit](#fa-traffic-light-monitoring-statement-tab)|  
|✅ <span title="Used to indicate normal operation">OK</span>|**Online**|The SQL Statement is valid and reports that no problems exist|<i class="fal fa-edit" aria-hidden="true"></i> [Edit](#fa-traffic-light-monitoring-statement-tab)|  

<aside aria-label="Tip" class="nodinite-note nodinite-note--tip">
<p class="nodinite-note__label" aria-hidden="true"><i class="far fa-fw fa-lightbulb"></i> Tip</p>
<div class="nodinite-note__content"><p>You can reconfigure the <strong>evaluated state</strong> for a <a href="https://docs.nodinite.com/administration/monitor-management/resources/features/what-is-a-resource/">Resource</a> using the <a href="https://docs.nodinite.com/administration/monitor-management/resources/features/expected-state/">Expected State</a> feature.</p></div>
</aside>

A statement raises a state with `THROW`: state `1` is **Error**, state `2` is **Warning**, and the exception message becomes the Log Text, for example *ERROR: 7 orders have waited more than an hour for their confirmation (limit 3)*. A statement that ends without an exception is **OK**. See the [Text Example](#text-example).

## <i class="fal fa-file" aria-hidden="true"></i> How do I add my custom coded TSQL Statements?

The [Database Monitoring Agent][] automatically monitors each configured **SQL Statement**. The <span class="nodinite-product-name" title="The node that unites different systems. Or as we call it Nodinite">Nodinite</span> Administrator can add new and modify existing **SQL Statements** using the [Remote Configuration][] dialogue for the [Database Monitoring Agent][]

## <i class="fal fa-globe" aria-hidden="true"></i> Global Configuration

In the [Remote Configuration][], open the **SQL Servers** tab and expand the **SQL Server Instance** accordion. Each instance has the tabs **General**, **Advanced**, **Backups**, **Jobs**, **Size checks**, **SSIS**, and **SQL Statements**. Click the **SQL Statements** tab.  
![The SQL Statements tab of SQL Server Instance localhost in the Remote Configuration, with three SQL Statement entries (7.12)][17]  
*The **SQL Statements** tab of an instance: one accordion per SQL Statement; a crossed-out entry is disabled.*

The <span class="nodinite-product-name" title="The node that unites different systems. Or as we call it Nodinite">Nodinite</span> Administrator can add new SQL Statements from the [Remote Configuration][] dialogue, detailed in [Add or manage a Monitoring Agent][Add or manage Monitoring Agent].  

From the **SQL Statements** tab in the **SQL Connection configuration**, click the <i class="fal fa-square-plus" aria-hidden="true"></i> **Add** button.  
>You can add any number of SQL Statements. Make sure that each one executes quickly, or you may end up hogging the agent, resulting in timeouts.

![The Remote Configuration of the Database agent with the SQL Statements tab of instance localhost and its Add button (7.12)][3]  
*Example to add a new configuration for SQL Statements using the **Add** button.*  

Then, expand the accordion.  
![A collapsed SQL Statement accordion, Contoso: Orders awaiting confirmation (7.12)][6]  

The following tabs exist:

* <i class="fal fa-cog" aria-hidden="true"></i> [General tab](#fa-cog-general-tab)
* <i class="fal fa-traffic-light" aria-hidden="true"></i> [Monitoring Statements tab](#fa-traffic-light-monitoring-statement-tab)
* <i class="fal fa-user-ninja" aria-hidden="true"></i> [User Action Scripts tab](#fa-user-ninja-user-action-scripts-tab)
* <i class="fal fa-user-secret" aria-hidden="true"></i> [Authentication tab](#fa-user-secret-authentication)

<aside aria-label="Note" class="nodinite-note nodinite-note--note">
<p class="nodinite-note__label" aria-hidden="true"><i class="far fa-fw fa-note"></i> Note</p>
<div class="nodinite-note__content"><p>Display names must be unique across all SQL Server, Azure SQL, and PostgreSQL entries of the agent; the agent refuses to save a name that two database types use (<em>Duplicate configuration names are not allowed across all database types</em>). The <strong>Display Name</strong> of a monitoring statement must be unique within its configuration, also across the configuration's SQL Statements, because it becomes the Resource name.</p></div>
</aside>

### <i class="fal fa-cog" aria-hidden="true"></i> General tab

To manage the essential configuration, click on the accordion to expand the details:  
![General tab of SQL Statement Contoso Orders DB with Enabled, Display Name, and Description, next to the tabs Monitoring Statements (2), User Action Scripts (1), and Authentication (7.13)][4]  
*The **General** tab of a SQL Statement; the tab names count its monitoring statements and action scripts.*

You can manage the following properties:

* <i class="fal fa-square-plus" aria-hidden="true"></i> **Enabled** – When checked, the monitoring statements of this SQL Statement are monitored. Clearing it removes the Resources of all its monitoring statements from the [Monitor Views][].  
* <i class="fal fa-font" aria-hidden="true"></i> **Display Name** – The name of the SQL Statement. It must be unique for each SQL Statement configuration. The SQL Statement isn't a Resource; its monitoring statements are.  
* <i class="fal fa-file-alt" aria-hidden="true"></i> **Description**

<h3 id="fa-traffic-light-monitoring-statement-tab"><i class="fal fa-traffic-light" aria-hidden="true"></i> Monitoring Statements tab</h3>

<sup><span class="nodinite-new-badge">New 7.13</span></sup>  
Click the **Monitoring Statements (n)** tab to manage the statements this SQL Statement runs. Each monitoring statement has its own accordion; click <i class="fal fa-square-plus" aria-hidden="true"></i> **Add** for another one. All of them use the connection of the [Authentication tab](#fa-user-secret-authentication).  
![The Monitoring Statements (2) tab of SQL Statement Contoso Orders DB with the monitoring statements Contoso Open Orders and Contoso Failed Orders and the Add button (7.13)][5]  
*The **Monitoring Statements** tab: one accordion per monitoring statement, and one Resource for each in the Monitor Views.*

![Add two monitoring statements to a new SQL Statement, save, and reload the configuration, animated walkthrough (7.13)][18]  
*Animated walkthrough: on the **SQL Statements** tab of a SQL Server instance, **Add** a SQL Statement, enter its connection string, add the monitoring statements *Contoso Open Orders* and *Contoso Failed Orders*, and **Save**. After a reload, both are kept.*

1. On the **SQL Statements** tab of the SQL Server instance, click <i class="fal fa-square-plus" aria-hidden="true"></i> **Add** and give the SQL Statement a **Display Name**.  
2. On the **Authentication** tab, enter the [Connection String][SQL Connection Strings].  
3. On the **Monitoring Statements (0)** tab, click <i class="fal fa-square-plus" aria-hidden="true"></i> **Add** once per monitoring statement and fill in its fields.  
4. Click **Save**.  

Expand a monitoring statement to edit it:  
![A monitoring statement, Contoso Failed Orders, with Enabled, Display Name, Description, Command Type Text, and a SELECT as Execute Command (7.13)][19]  
*One monitoring statement. Its **Display Name** is the Resource name in the [Monitor Views][].*

* <i class="fal fa-square-check" aria-hidden="true"></i> **Enabled** – When checked, this monitoring statement is monitored.
* <i class="fal fa-font" aria-hidden="true"></i> **Display Name** – The name of the Resource in the Monitor Views. Required while the monitoring statement is enabled, and unique within the configuration, also across its SQL Statements.
* <i class="fal fa-file-alt" aria-hidden="true"></i> **Description** – The user-friendly description of the Resource.
* <i class="fal fa-play" aria-hidden="true"></i> **Command Type** – The **Type** of 'SQL Command', select one of the following:
  * **Text** – For AdHoc TSQL Statements
  * **Stored Procedure** – For existing parameterless stored procedures
* <i class="fal fa-play" aria-hidden="true"></i> **Execute Command** – The SQL command(s) to execute. Required for each enabled monitoring statement of an enabled SQL Statement.  

An enabled monitoring statement without a **Display Name** is marked red with *Display Name is required*, and the configuration isn't saved.  
![An enabled monitoring statement with an empty Display Name, marked red with Display Name is required (7.13)][20]  
*The **Display Name** is required while the monitoring statement is enabled.*

Two monitoring statements with the same **Display Name** in one configuration stop the save with *400 Configuration Error*.  
![400 Configuration Error: Duplicate monitoring statement DisplayNames found for SQL Server localhost, make sure each monitoring statement DisplayName is unique within the configuration, also across its SQL Statements (7.13)][21]  
*The error names the SQL Server configuration that holds the duplicate.*

A SQL Statement from an earlier agent version, with its single command, is migrated once: the command becomes its first monitoring statement.

<aside aria-label="Important" class="nodinite-note nodinite-note--important">
<p class="nodinite-note__label" aria-hidden="true"><i class="far fa-fw fa-message-exclamation"></i> Important</p>
<div class="nodinite-note__content"><p>This feature can execute custom TSQL with significant impact if it is misconfigured.</p><p>Use the centralized security guide for least privilege, dedicated connection strings, impersonation boundaries, and credential isolation:</p><p><i class="fal fa-shield-halved" aria-hidden="true"></i> <a href="https://docs.nodinite.com/logging-and-monitoring/database/troubleshooting/secure-custom-database-scripts-and-actions/">Secure Custom Database Scripts and Actions</a></p></div>
</aside>

#### <i class="fal fa-edit" aria-hidden="true"></i> Stored Procedure

Execute one or more stored procedures in the SQL Server database provided by the [connection string][SQL Connection Strings]. For example, enter `[YourCustomProcedure]` or the full path.

``` sql
[Database].[dbo].[YourCustomProcedure]
```

*Here's an example of stored procedure call using a full path.*

<aside aria-label="Info" class="nodinite-note nodinite-note--info">
<p class="nodinite-note__label" aria-hidden="true"><i class="far fa-fw fa-square-info"></i> Info</p>
<div class="nodinite-note__content"><p>If you are using a <strong>Stored Procedure</strong>, you MUST enter the name with just one (1) line of code in the text field; Otherwise the evaluation will fail.</p></div>
</aside>

### <i class="fal fa-user-ninja" aria-hidden="true"></i> User Action Scripts tab

Add entries in the 'User Action Scripts' tab to allow your end-users to execute scripts on demand. The scripts belong to the SQL Statement: **Show Action Scripts** on any of its monitoring statements lists them, so a SQL Statement needs at least one enabled monitoring statement for its scripts to show in a [Monitor View][Monitor Views].  
![User Action Scripts (1) tab of SQL Statement Contoso Orders DB with the action script List open orders and the Add button (7.13)][2]  
*Example of the User Action Scripts tab for on-demand script execution.*

A SQL Statement may have any number of scripts.

Click the <i class="fal fa-square-plus" aria-hidden="true"></i> **Add** button to add a script.

Then, expand the accordion.  
![A collapsed action script accordion, Action: Show the orders awaiting confirmation (7.12)][1]  

You can then fill out the following properties:  

* <i class="fal fa-square-check" aria-hidden="true"></i> **Enabled** – When checked, this SQL Action Script is visible in the end-user list of executable scripts
* <i class="fal fa-tag" aria-hidden="true"></i> **Display Name** – The user-friendly name of this action script
* <i class="fal fa-align-left" aria-hidden="true"></i> **Description** – User-friendly description for this SQL Action Script
* <i class="fal fa-play" aria-hidden="true"></i> **Command Type** – The type of SQL command
  * Text
  * Stored Procedure
* <i class="fal fa-play" aria-hidden="true"></i> **Execute Command** – The SQL command to execute  
  ![The action script List open orders with Enabled, Display Name, the Description The open orders per integration, Command Type Text, and a SELECT as Execute Command (7.13)][11]  
  *Example of a script entry for on-demand execution.*

### <i class="fal fa-user-secret" aria-hidden="true"></i> Authentication

<sup><span class="nodinite-new-badge">New 6.2.0.0</span></sup>  
Each SQL Statement runs with its own [connection string][SQL Connection Strings], and can impersonate a domain user. All its monitoring statements and User Action Scripts use this one authentication.  
![Authentication tab of SQL Statement Contoso Orders DB with the masked Connection String, Use Impersonation checked, the Domain User CONTOSO svc-monitor, and the masked Password (7.13)][12]  
*The **Authentication** tab: one connection for every monitoring statement of the SQL Statement.*

* <i class="fal fa-plug" aria-hidden="true"></i> **Connection String** – The [connection string][SQL Connection Strings] used by all monitoring statements of this SQL Statement. Required while the SQL Statement is enabled: the agent refuses to save an enabled SQL Statement without one (*requires a connection string*). A disabled SQL Statement can be saved without it.  
  ![A disabled SQL Statement, marked with the ban icon, with an empty Connection String on its Authentication tab (7.13)][22]  
  *A disabled SQL Statement (ban icon) may have an empty **Connection String**.*
* <i class="fal fa-user-shield" aria-hidden="true"></i> **Use Impersonation** – Run the statement as the domain user below. Required when the connection string uses Integrated Security; otherwise the agent refuses to save (*uses Integrated Security in its connection string. Please enable 'Use Impersonation'...*).
* <i class="fal fa-user" aria-hidden="true"></i> **Domain User** – The name of the Windows user account. Format: DOMAIN\User
* <i class="fal fa-key" aria-hidden="true"></i> **Password** – The password for the provided domain user

<aside aria-label="Important" class="nodinite-note nodinite-note--important">
<p class="nodinite-note__label" aria-hidden="true"><i class="far fa-fw fa-message-exclamation"></i> Important</p>
<div class="nodinite-note__content"><p><strong>CRITICAL: DO NOT USE THE AGENT'S SERVICE ACCOUNT</strong></p><p>The credentials provided in the Authentication tab <strong>MUST NOT be the same account</strong> that runs the Database Monitoring Agent service. The agent runs with elevated privileges, and reusing those credentials defeats the isolation model.</p><p><strong><i class="fal fa-ban" aria-hidden="true"></i> Prohibited:</strong> Using the agent service account (for example <code>DOMAIN\NodiniteAgentService</code>) for SQL Statement execution.<br>
<strong>✅ Required:</strong> Use dedicated SQL credentials with least privilege.</p><p>For the complete baseline and examples, see <i class="fal fa-shield-halved" aria-hidden="true"></i> <a href="https://docs.nodinite.com/logging-and-monitoring/database/troubleshooting/secure-custom-database-scripts-and-actions/">Secure Custom Database Scripts and Actions</a>.</p></div>
</aside>

### <i class="fal fa-save" aria-hidden="true"></i> Save

You must click '**Save**' or '**Save and close**' for changes to persist. The new settings/thresholds are evaluated on the next synchronization.  
![Save, Save and close, and Close buttons of the Remote Configuration dialog (7.12)][png_SaveAndClose]  
*Here's an example of the **Save** options.*

<aside aria-label="Note" class="nodinite-note nodinite-note--note">
<p class="nodinite-note__label" aria-hidden="true"><i class="far fa-fw fa-note"></i> Note</p>
<div class="nodinite-note__content"><p>Depending on the synchronization interval set for the agent, there might be a delay before the <span class="nodinite-product-name" title="The node that unites different systems. Or as we call it Nodinite">Nodinite</span> <a href="https://docs.nodinite.com/getting-started/overview/">Web Client</a> reflects the change. You can choose to force the agent to synchronize from the configuration of the <a href="https://docs.nodinite.com/administration/monitor-management/monitor-agents/features/what-is-a-monitor-agent/">Monitoring Agents</a>.</p></div>
</aside>

**Save and close** saves and closes the dialogue.  
**Close** closes the dialogue without saving any changes.

## <i class="fal fa-bolt" aria-hidden="true"></i> Actions

The following [Remote Actions][] are available in the **Control Center** part of the **Action** menu:  

* <i class="fal fa-circle-info" aria-hidden="true"></i> [Details](#fa-circle-info-details)
* <i class="fal fa-bolt" aria-hidden="true"></i> [Show Action Scripts](#fa-bolt-execute-sql-script)

![Action menu of the monitoring statement Contoso Open Orders with Details and Show Action Scripts under Control Center (7.13)][7]  
*The **Control Center** part of the **Action** menu of a monitoring statement.*

### <i class="fal fa-circle-info" aria-hidden="true"></i> Details

Click **Details** in the **Action** menu. The **Details** modal shows the **Server**, **Database**, and **Application** of the monitoring statement and an editable **Description**, with **Save**; it does not run the statement or show a result.  
![Details of the monitoring statement Contoso Open Orders with Server localhost, Database MSDB, Application localhost, and the saved Description Orders waiting for INT001: Orders (7.13)][14]  
*The **Details** modal with a Description saved from the Monitor View.*

<h3 id="fa-bolt-execute-sql-script"><i class="fal fa-bolt" aria-hidden="true"></i> Show Action Scripts</h3>

You can **execute** pre-defined **TSQL** scripts and immediately see the result. The <span class="nodinite-product-name" title="The node that unites different systems. Or as we call it Nodinite">Nodinite</span> Administrator manages the collection of scripts in the [User Action Scripts tab](#fa-user-ninja-user-action-scripts-tab).

![Run the action script List open orders from the monitoring statement Contoso Open Orders: Action menu, Show Action Scripts, Execute and confirm, and the output table, animated walkthrough (7.13)][23]  
*Animated walkthrough: open the **Action** menu of the monitoring statement *Contoso Open Orders*, click **Show Action Scripts**, **Execute** *List open orders*, confirm, and read the output table.*

Click **Show Action Scripts** in the **Action** menu. The **Action Scripts** dialog lists the enabled scripts of the SQL Statement the monitoring statement belongs to, each with an <i class="fal fa-bolt" aria-hidden="true"></i> **Execute** button; every monitoring statement of that SQL Statement offers the same scripts. A script runs with the SQL Statement's connection string.  
![Action Scripts dialog of Contoso Open Orders with the script List open orders and its Execute button (7.13)][8]  
*The **Action Scripts** dialog of a monitoring statement.*

Click <i class="fal fa-bolt" aria-hidden="true"></i> **Execute** on a script and confirm the intent: *Execute action? Are you sure you want to execute the SQL script '…'?*  
![Execute action? confirmation for the SQL script Show the orders awaiting confirmation (7.12)][9]  
*Confirmation dialog for script execution.*

The result shows under **Output from** *script name*, with a **Table** and a **Raw** tab, a timestamp, the row count, and the duration.  
![Action Scripts dialog with Output from List open orders: a table with the row INT001: Orders and 3 open orders, the timestamp, the row count, and the duration (7.13)][10]  
*The result of a script run on demand.*

___

## <i class="fal fa-code" aria-hidden="true"></i> Examples

There are two ways to provide the outcome (Monitoring state of the Resource) based on the logic in your custom-built **SQL Statements**:

|#|Text/AdHoc|Stored Procedure|  
|---|:---:|:---:|  
|1. **Select + return code**|❌ Not supported|✅ Supported|  
|2. **Select + throw (raiserror)**|✅ Supported|✅ Supported|  

>Use a supported implementation according to the use of either Text/AdHoc or Stored Procedures.

Internally, the <span class="nodinite-product-name" title="The node that unites different systems. Or as we call it Nodinite">Nodinite</span> [Database Monitoring Agent][Database Monitoring Agent] executes the [Execute Scalar][] method. <span class="nodinite-product-name" title="The node that unites different systems. Or as we call it Nodinite">Nodinite</span> picks up data from the first column from the first returned row. The extracted value is set as the **Log Text** unless you raised an exception.

<aside aria-label="Important" class="nodinite-note nodinite-note--important">
<p class="nodinite-note__label" aria-hidden="true"><i class="far fa-fw fa-message-exclamation"></i> Important</p>
<div class="nodinite-note__content"><p>Ensure your logic does not perform any processing or have side effects. We recommend that all TSQL commands execute within a second or so. This means you may need to adjust the background process and involve <a href="https://docs.nodinite.com/logging-and-monitoring/database/features/jobs/overview/">SQL Jobs</a> (or other scheduled background tasks) to perform processing and then the logic here merely gets the result.</p></div>
</aside>

### 1. Select + return code

The Log Text presented for the monitoring statement (the [Resource][Resources]) comes from your last SELECT statement (1st row, 1st column). If you do not select anything, the **Log Text** is empty.  

|Return Code|Evaluated State|LogText|  
|---|---|---|  
|**= 0**|**OK**|From SELECT operation (1st column)|  
|**< 0**|**Error**|From SELECT operation (1st column)|  
|**> 0**|**Warning**|From SELECT operation (1st column)|  

### 2. Select + throw (raiserror)

The Log Text presented for the monitoring statement (the [Resource][Resources]) comes from your last SELECT statement (1st row, 1st column) or from the Exception. If you do not select anything, the **Log Text** is empty.  

|Return Code|Evaluated State|LogText|  
|---|---|---|  
|No exception raised|**OK**|From SELECT operation (1st column)|  
|Throw exception with State = 1|**Error**|From exception text|  
|Throw exception with State > 1|**Warning**|From exception text|  

### Text Example

Example of using the SQL Statement with Command Type set to **Text**. This example counts the rows in the actual table. Depending on your logic, different states can be returned.  

```sql
DECLARE @rowCount INT, 
        @log VARCHAR(256), 
        @errorLimit INT = 3, 
        @warningLimit INT = 1  
  
SELECT @rowCount = COUNT(1) FROM [ConnectionFailures]  
            
IF (@rowCount > @errorLimit)  
   BEGIN  
      SET @log = 'ERROR Number of connection failures exceeded ' + CAST (@errorLimit AS VARCHAR(18));  
      THROW 51000, @log, 1;  
   END  
ELSE IF (@rowCount > @warningLimit)  
   BEGIN  
      SET @log = 'WARNING number of connection failures exceeded ' + CAST (@warningLimit AS VARCHAR(18));  
      THROW 51000, @log, 2;  
   END  
ELSE  
   BEGIN  
      SELECT 'OK'  
   END  
```

<aside aria-label="Note" class="nodinite-note nodinite-note--note">
<p class="nodinite-note__label" aria-hidden="true"><i class="far fa-fw fa-note"></i> Note</p>
<div class="nodinite-note__content"><p>THROW is available in SQL Server 2012 and later. In SQL Server 2008 R2, use RAISERROR (@log, 16, 1); RAISERROR(Message, Severity, State). The <strong>Severity</strong> should be set to 16. Such a high value is required to stop the execution of the query.</p></div>
</aside>

### Stored Procedure example

Example of using the SQL Statement with Command Type set to **Stored Procedure**

```sql
[SP_CheckConnectionFailures]
```

Example of the Stored Procedure (existing in the actual database):  

```sql
USE [MyDatabase]
GO

SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER OFF
GO

CREATE PROCEDURE [dbo].[SP_CheckConnectionFailures] 
AS

BEGIN
   SET NOCOUNT ON;
            
   DECLARE  @rowCount INT,
            @errorLimit INT = 3,
            @warningLimit INT = 1,
            @ret INT = 0,
            @log VARCHAR(256)
            
  SELECT @rowCount = COUNT(1) from [dbo].[ConnectionFailures]
            
  IF (@rowCount > @errorLimit)
     BEGIN
        SET @log = 'ERROR: The number of connection failures was exceeded: ' + CAST (@errorLimit AS VARCHAR(18));  
        SELECT @log
        SET @ret = -10
     END
  ELSE IF (@rowCount> @warningLimit)
     BEGIN
        SET @log = 'WARNING: The number of connection failures was exceeded: ' + CAST (@warningLimit AS VARCHAR(18));  
        SELECT @log
        SET @ret = 10
     END
  ELSE
     BEGIN
        SELECT 'OK'
     END
  RETURN @ret

END -- Procedure
```

<aside aria-label="Note" class="nodinite-note nodinite-note--note">
<p class="nodinite-note__label" aria-hidden="true"><i class="far fa-fw fa-note"></i> Note</p>
<div class="nodinite-note__content"><p>There is currently no way to provide arguments to the  <strong>Stored Procedures</strong>. Use <strong>Command Type</strong> set to <strong>Text</strong> and pass arguments to the Stored Procedure from your Text/AdHoc TSQL code.</p></div>
</aside>

___

## <i class="fal fa-hand-point-right" aria-hidden="true"></i> Next Steps

* <i class="fal fa-display" aria-hidden="true"></i> [Add or manage Monitor View][]  

## <i class="fal fa-link-horizontal" aria-hidden="true"></i> Related Topics

* <i class="fal fa-database" aria-hidden="true"></i> [Azure SQL Statements][]  
* <i class="fal fa-database" aria-hidden="true"></i> [PostgreSQL SQL Statements][]  
* <i class="fal fa-database" aria-hidden="true"></i> [Database Monitoring Agent][]  
* <i class="fal fa-folder" aria-hidden="true"></i> [SQL Categories][]  
* <i class="fal fa-lightbulb-on" aria-hidden="true"></i> [Resources][]  
* <i class="fal fa-cloud-arrow-down" aria-hidden="true"></i> [Monitoring Agents][]  
* <i class="fal fa-display" aria-hidden="true"></i> [Monitor Views][]  
* <i class="fal fa-rectangle-terminal" aria-hidden="true"></i> [PowerShell Monitoring][] - Similar monitoring approach using custom PowerShell scripts  
* <i class="fal fa-shield-halved" aria-hidden="true"></i> [Secure Custom Database Scripts and Actions][] - Centralized guidance for secure SQL statement and action-script execution  

[0]:https://docs.nodinite.com/media/Documentation%20Pictures/MonitorAgent/Database/SQLStatements_MonitorView.png
[1]:https://docs.nodinite.com/media/Documentation%20Pictures/MonitorAgent/SQL/SqlStatements/EmptyAccordionScript.png
[2]:https://docs.nodinite.com/media/Documentation%20Pictures/MonitorAgent/SQL/SqlStatements/UserActionScriptsTab.png
[3]:https://docs.nodinite.com/media/Documentation%20Pictures/MonitorAgent/SQL/SqlStatements/AddConfigEntry.png
[4]:https://docs.nodinite.com/media/Documentation%20Pictures/MonitorAgent/SQL/SqlStatements/GeneralTab.png
[5]:https://docs.nodinite.com/media/Documentation%20Pictures/MonitorAgent/Database/SQLStatements_Config_MonitoringStatements.png
[6]:https://docs.nodinite.com/media/Documentation%20Pictures/MonitorAgent/SQL/SqlStatements/EmptyAccordion.png
[7]:https://docs.nodinite.com/media/Documentation%20Pictures/MonitorAgent/Database/SQLStatements_Actions.png
[8]:https://docs.nodinite.com/media/Documentation%20Pictures/MonitorAgent/Database/SQLStatements_ActionScripts.png
[9]:https://docs.nodinite.com/media/Documentation%20Pictures/MonitorAgent/SQL/SqlStatements/ExecuteScriptDialog.png
[10]:https://docs.nodinite.com/media/Documentation%20Pictures/MonitorAgent/Database/SQLStatements_ActionScripts_Output.png
[11]:https://docs.nodinite.com/media/Documentation%20Pictures/MonitorAgent/SQL/SqlStatements/ScriptEntry.png
[12]:https://docs.nodinite.com/media/Documentation%20Pictures/MonitorAgent/Database/SQLStatements_Config_Authentication.png
[14]:https://docs.nodinite.com/media/Documentation%20Pictures/MonitorAgent/Database/SQLStatements_Details_DescriptionSaved.png
[16]:https://docs.nodinite.com/media/Documentation%20Pictures/MonitorAgent/SQL/SqlStatements/SqlStatement_Error.gif
[17]:https://docs.nodinite.com/media/Documentation%20Pictures/MonitorAgent/SQL/RemoteConfig/SqlStatementsTab.png
[18]:https://docs.nodinite.com/media/Documentation%20Pictures/MonitorAgent/Database/SQLStatements_AddMonitoringStatements.gif
[19]:https://docs.nodinite.com/media/Documentation%20Pictures/MonitorAgent/Database/SQLStatements_Config_MonitoringStatement.png
[20]:https://docs.nodinite.com/media/Documentation%20Pictures/MonitorAgent/Database/SQLStatements_Config_MonitoringStatement_DisplayNameRequired.png
[21]:https://docs.nodinite.com/media/Documentation%20Pictures/MonitorAgent/Database/SQLStatements_Config_DuplicateMonitoringStatement_Message.png
[22]:https://docs.nodinite.com/media/Documentation%20Pictures/MonitorAgent/Database/SQLStatements_Config_DisabledSqlStatement_NoConnectionString.png
[23]:https://docs.nodinite.com/media/Documentation%20Pictures/MonitorAgent/Database/SQLStatements_RunActionScript.gif

[Add or manage Monitor View]:https://docs.nodinite.com/administration/monitor-management/monitor-views/features/add-or-manage-monitor-view/
[Add or manage Monitoring Agent]:https://docs.nodinite.com/administration/monitor-management/monitor-agents/features/add-or-manage-monitor-agent/
[Alarm Plugins]:https://docs.nodinite.com/administration/settings/alarm-plugins/features/what-is-an-alarm-plugin/
[Azure SQL Statements]:https://docs.nodinite.com/logging-and-monitoring/database/features/sql-statements/azure-sql-statements/
[Categories]:https://docs.nodinite.com/administration/monitor-management/categories/features/what-is-a-category/
[Database Monitoring Agent]:https://docs.nodinite.com/logging-and-monitoring/database/overview/
[Execute Scalar]:https://learn.microsoft.com/en-us/dotnet/api/system.data.sqlclient.sqlcommand.executescalar?redirectedfrom=MSDN&view=netframework-4.8
[Expected State]:https://docs.nodinite.com/administration/monitor-management/resources/features/expected-state/
[Monitor Views]:https://docs.nodinite.com/administration/monitor-management/monitor-views/features/what-is-a-monitor-view/
[Monitoring Agents]:https://docs.nodinite.com/administration/monitor-management/monitor-agents/features/what-is-a-monitor-agent/
[png_SaveAndClose]:https://docs.nodinite.com/media/Documentation%20Pictures/MonitorAgent/SQL/SaveAndClose.png
[PostgreSQL SQL Statements]:https://docs.nodinite.com/logging-and-monitoring/database/features/sql-statements/postgresql-sql-statements/
[PowerShell Monitoring]:https://docs.nodinite.com/logging-and-monitoring/windows-server/features/powershell/
[Prerequisites for Database Monitoring Agent]:https://docs.nodinite.com/logging-and-monitoring/database/getting-started/prerequisites/
[Remote Actions]:https://docs.nodinite.com/getting-started/monitor/remote-actions/
[Remote Configuration]:https://docs.nodinite.com/logging-and-monitoring/database/getting-started/configuration/
[Resources]:https://docs.nodinite.com/administration/monitor-management/resources/features/what-is-a-resource/
[Secure Custom Database Scripts and Actions]:https://docs.nodinite.com/logging-and-monitoring/database/troubleshooting/secure-custom-database-scripts-and-actions/
[SQL Categories]:https://docs.nodinite.com/logging-and-monitoring/database/features/overview/
[SQL Connection Strings]:https://docs.nodinite.com/install-and-update/troubleshooting/sql-server/connection-strings/
[SQL Jobs]:https://docs.nodinite.com/logging-and-monitoring/database/features/jobs/overview/
[SQL Server Options]:https://docs.nodinite.com/install-and-update/troubleshooting/sql-server/sql-server-options/
[Users]:https://docs.nodinite.com/administration/access-management/users/features/what-is-a-user/
[Web Client]:https://docs.nodinite.com/getting-started/overview/