---
title: "Automate Safe Removal of Old Nodinite Log Databases: SQL Server Agent Job Guide"
description: "Automate the safe removal of historical Nodinite Log Databases using SQL Server Agent jobs. Complete beginner-friendly step-by-step guide: create the job, name it, add scripts, set a schedule, and monitor results in SSMS."
---

# Remove historical Log Databases

<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><span class="nodinite-product-name" title="The node that unites different systems. Or as we call it Nodinite">Nodinite</span> can perform shrinking of <a href="https://docs.nodinite.com/core-services/log-databases/overview/">Log Databases</a> to manage disk space, but this does not remove the database itself. See the <a href="https://docs.nodinite.com/administration/settings/system-parameters/overview/">System Parameter</a> '<a href="https://docs.nodinite.com/administration/settings/system-parameters/databasemaintenance/">DatabaseMaintenance</a>' for more information on this capability.</p></div>
</aside>

Easily automate the safe removal of historical <span class="nodinite-product-name" title="The node that unites different systems. Or as we call it Nodinite">Nodinite</span> Log Databases that are no longer required by your business. This guide empowers you to:

* ✅ Maintain compliance and optimize storage with automated cleanup  
* ✅ Reduce manual DBA workload and risk of human error  
* ✅ Follow best practices for data retention and system stability  
* ✅ Use SQL Server Agent jobs for reliable, repeatable maintenance  

<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>On this page, you will learn how to <strong>remove</strong> historical <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/core-services/log-databases/overview/">Log Databases</a> by creating an automated job inside SQL Server. You do not need to be a database expert to follow this guide.</p></div>
</aside>

<span class="nodinite-product-name" title="The node that unites different systems. Or as we call it Nodinite">Nodinite</span> automatically creates new databases when the following [System Parameters][] are met:

* <i class="fal fa-calendar-day" aria-hidden="true"></i> [DaysToSplitDatabaseOn][] — Create a new database after this many days.
* <i class="fal fa-sort-size-up-alt" aria-hidden="true"></i> [SizeToSplitDatabaseOn][] — Create a new database when exceeding this size.

<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><span class="nodinite-product-name" title="The node that unites different systems. Or as we call it Nodinite">Nodinite</span> does <strong>NOT</strong> automatically remove Log Databases. You must establish a routine to remove these according to your policy. Dropping <a href="https://docs.nodinite.com/core-services/log-databases/overview/">Log Databases</a> carries a high risk, including potential data loss and system instability. Always verify you are removing the correct set and use your own discretion.</p></div>
</aside>

---

## Understanding Data Retention

It is safe to remove empty old [Log Databases][]. However, even empty historical [Log Databases][] consume disk space and create overhead — CPU, disk I/O, and backup pressure. This process is designed to minimize risk and optimize performance.

Data retention in the [Log Databases][] is governed by [System Parameters][]. [Log Events][Log Event] are individually removed based on the [Message Type][Message Types]. The following [System Parameters][] specify how long to keep events and data by default:

* <i class="fal fa-calendar-day" aria-hidden="true"></i> [DaysToKeepMessageEventsDefault][]
* <i class="fal fa-calendar-day" aria-hidden="true"></i> [DaysToKeepMessageContextDefault][]
* <i class="fal fa-calendar-day" aria-hidden="true"></i> [DaysToKeepMessageDataDefault][]
* <i class="fal fa-calendar-day" aria-hidden="true"></i> [DaysToKeepMonitorEvents][]

A [Log Database][Log Databases] is safe to remove once all its data has been purged according to your retention policy **and** the `EndDate` for that database has passed. The scripts below automatically detect such databases — you only need to set the variables.

<div class="mermaid">
flowchart TB
    New["fa:fa-database Online Log Database<br/>created by the Logging Service"] -->|"Size or days reached"| Archive["fa:fa-box-archive Archive Log Database<br/>EndDate set"]
    Archive -->|"Retention purges Log Events"| Expired["fa:fa-hourglass-end Expired<br/>EndDate older than @days"]
    Expired -->|"Job step 1: Script A"| Dropped["fa:fa-trash Database dropped<br/>on SQL Server"]
    Dropped -->|"Job step 2: Script B"| Clean["fa:fa-broom Row removed<br/>from LogTables"]
    Dropped -.->|"Step 1 fails: job quits"| Stop["fa:fa-ban Step 2 never runs"]
    style New fill:#2678BD
    style Archive fill:#3F827B
    style Expired fill:#FFD525
    style Dropped fill:#E47528
    style Clean fill:#93d16d
    style Stop fill:#c33d34
</div>

*Diagram: the life of a [Log Database][Log Databases]. The [Logging Service][] creates a new online Log Database when [SizeToSplitDatabaseOn][] or [DaysToSplitDatabaseOn][] is reached; the previous one becomes an archive. Retention [System Parameters][] purge its [Log Events][Log Event], and once its `EndDate` is older than `@days`, the SQL Server Agent job on this page drops it (Script A) and then removes its row from the [Configuration Database][ConfigDB] (Script B). Red marks the safety stop when Script A fails.*

---

## What You Need Before Starting

Make sure you have the following before continuing:

* ✅ **SQL Server Management Studio (SSMS)** installed on your computer — [Download SSMS free from Microsoft][SSMS Download]<sup><i class="fal fa-arrow-up-right-from-square" aria-hidden="true"></i></sup>
* ✅ A SQL Server login with **sysadmin** privileges on the server that hosts the <span class="nodinite-product-name" title="The node that unites different systems. Or as we call it Nodinite">Nodinite</span> [Configuration Database][ConfigDB]
* ✅ The **SQL Server Agent** service is **running** on that SQL Server instance (check with your DBA if unsure)
* ✅ The name of your <span class="nodinite-product-name" title="The node that unites different systems. Or as we call it Nodinite">Nodinite</span> [Configuration Database][ConfigDB] — for example, `Nodinite_Prod_Config`
* ✅ The prefix of your <span class="nodinite-product-name" title="The node that unites different systems. Or as we call it Nodinite">Nodinite</span> Log Databases — for example, `Nodinite_Prod_Log_`

Use [SQL Server Sysadmin Requirements][] to align DBA policy decisions with installation, first database creation, and optional maintenance behavior.

<aside aria-label="Warning" class="nodinite-note nodinite-note--warning">
<p class="nodinite-note__label" aria-hidden="true"><i class="far fa-fw fa-triangle-exclamation"></i> Warning</p>
<div class="nodinite-note__content"><p><strong><a href="https://docs.nodinite.com/install-and-update/troubleshooting/sql-server/sql-server-options/#sql-server-express">SQL Server Express</a> does not include SQL Server Agent.</strong> If you are running SQL Server Express (including SQL Server 2025 Express), use a Windows <a href="https://docs.nodinite.com/logging-and-monitoring/windows-server/features/scheduled-tasks/">Scheduled Task</a> with <code>sqlcmd</code> as an alternative. Move to Standard/Enterprise only if your operations policy requires SQL Server Agent.</p></div>
</aside>

---

## The Scripts

The job uses two T-SQL scripts that must run **in sequence**. Never swap the order — Step 1 removes the physical databases, Step 2 removes the records from <span class="nodinite-product-name" title="The node that unites different systems. Or as we call it Nodinite">Nodinite</span>. If Step 1 fails, Step 2 must never run.

### Script variables

Update the following four variables at the top of **both** scripts to match your environment before using them in the job:

|Variable|Description|Example|
|---|---|---|
|`@prefix`|The prefix portion of your <span class="nodinite-product-name" title="The node that unites different systems. Or as we call it Nodinite">Nodinite</span> Log Database names|v7: `Nodinite_Prod_Log_`<br/>Created by v6: `NodiniteLog_Prod_`|
|`@configDB`|The name of the <span class="nodinite-product-name" title="The node that unites different systems. Or as we call it Nodinite">Nodinite</span> [Configuration Database][ConfigDB]|v7: `Nodinite_Prod_Config`<br/>Created by v6: `NodiniteConfig_Prod`|
|`@days`|How old (in days) a database must be before it is eligible for removal — must be a positive integer|`180`|
|`@managedInstance`|`1` if the Log Databases are hosted on **Azure SQL Managed Instance**, otherwise `0` — see [Azure SQL Managed Instance](#azure-sql-managed-instance)|`0`|

<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>Not sure what your prefix and config database are called? Open SSMS, connect, and expand <strong>Databases</strong> in Object Explorer. The names depend on the <span class="nodinite-product-name" title="The node that unites different systems. Or as we call it Nodinite">Nodinite</span> version the databases were <strong>created</strong> with, not the version you run today, because upgrading to v7 does not rename existing databases:</p><ul>
<li>v7 and later: <code>Nodinite_&lt;Environment&gt;_Log_…</code> and <code>Nodinite_&lt;Environment&gt;_Config</code></li>
<li>v6 and earlier: <code>NodiniteLog_&lt;Environment&gt;_…</code> and <code>NodiniteConfig_&lt;Environment&gt;</code></li>
</ul><p>If you have Log Databases with <strong>both</strong> naming patterns, the scripts only match one prefix per run. Create one job per prefix, or keep the old prefix until those databases are gone. See <a href="https://docs.nodinite.com/core-services/log-databases/overview/">Log Databases</a> for the naming convention.</p></div>
</aside>

### Local vs Remote Log Databases

Before using the scripts, check where your Log Databases physically reside. Run the following query on your Config DB:

``` sql
SELECT [Database], [Server], [IsRemoteServer] FROM [dbo].[LogTables] ORDER BY [StartDate]
```

|**IsRemoteServer**|Meaning|Which script to use|
|---|---|---|
|`0`|The Log Database is on the **same SQL Server instance** as the Config DB|Run the job on the **Config DB server** — this is the standard case|
|`1`|The Log Database is on a **different SQL Server instance** (connected via a [linked server][Linked Servers])|Run the job **on the remote SQL Server** that hosts the Log Databases|
|`1`|The Log Databases are on **Azure SQL Managed Instance**|Set `@managedInstance = 1` and run the job on the Managed Instance — see [Azure SQL Managed Instance](#azure-sql-managed-instance)|

<h4 id="azure-sql-managed-instance">Azure SQL Managed Instance</h4>

On Azure SQL Managed Instance, Log Databases are registered in <span class="nodinite-product-name" title="The node that unites different systems. Or as we call it Nodinite">Nodinite</span> with `IsRemoteServer = 1`, and Managed Instance does not allow `ALTER DATABASE … SET SINGLE_USER`. Set `@managedInstance = 1` in **both** scripts to handle this:

|Script behavior|`@managedInstance = 0` (SQL Server)|`@managedInstance = 1` (Managed Instance)|
|---|---|---|
|Selects Log Databases with|`IsRemoteServer = 0`|`IsRemoteServer = 1`|
|Disconnects open sessions before the drop|Yes — `SET SINGLE_USER WITH ROLLBACK IMMEDIATE`|No — not supported on Managed Instance|

<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>Without <code>SINGLE_USER</code>, <code>DROP DATABASE</code> fails if a session still uses the Log Database. The job then stops at Script A with a failure and Script B does not run, so <span class="nodinite-product-name" title="The node that unites different systems. Or as we call it Nodinite">Nodinite</span> and SQL Server stay in sync. Check the job history and run the job again when the database is no longer in use.</p></div>
</aside>

<aside aria-label="Warning" class="nodinite-note nodinite-note--warning">
<p class="nodinite-note__label" aria-hidden="true"><i class="far fa-fw fa-triangle-exclamation"></i> Warning</p>
<div class="nodinite-note__content"><p>On SQL Server (<code>@managedInstance = 0</code>), Script A filters <code>AND [IsRemoteServer] = 0</code> as a safety guard. If all your rows show <code>IsRemoteServer = 1</code>, the script will produce <strong>no DROP statements</strong> — only <code>USE [master]</code>. Before assuming your databases are truly remote, <strong>verify in SSMS</strong> whether the Log Databases actually appear on the same server as the Config DB. If they do, the flag is incorrect in <span class="nodinite-product-name" title="The node that unites different systems. Or as we call it Nodinite">Nodinite</span> and must be fixed — see <a href="#fix-incorrect-isremoteserver-flag">Fix incorrect IsRemoteServer flag</a> below.</p></div>
</aside>

<h4 id="fix-incorrect-isremoteserver-flag">Fix Incorrect IsRemoteServer Flag</h4>

This section does not apply to Azure SQL Managed Instance, where `IsRemoteServer = 1` is expected. If your Log Databases are visible on the same SQL Server instance as your Config DB in SSMS, but `LogTables` shows `IsRemoteServer = 1`, the **Remote Server** checkbox was incorrectly ticked when those databases were registered in <span class="nodinite-product-name" title="The node that unites different systems. Or as we call it Nodinite">Nodinite</span>.

Fix this in the <span class="nodinite-product-name" title="The node that unites different systems. Or as we call it Nodinite">Nodinite</span> [Web Client][]:

1. Navigate to **Administration > Settings > [Log Databases][Log Databases Admin]**
2. Click **Edit** on each affected Log Database entry
3. Uncheck the **Remote Server** checkbox
4. Click **Save**
5. Repeat for all affected entries

Once all entries show `IsRemoteServer = 0`, re-run the diagnostic query above to confirm, then proceed with the scripts.

<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>See <a href="https://docs.nodinite.com/administration/settings/log-databases/add-or-manage-log-database/">Add or Manage a Log Database</a> for full details on each field, including the <strong>Remote Server</strong> checkbox.</p></div>
</aside>

### Job step execution plan

|Job Step|On success|On failure|What it does|
|---|---|---|---|
|<i class="fal fa-forward-step" aria-hidden="true"></i> [Script A](#script-a-remove-databases-from-sql-server)|Go to next step|Quit — report failure|Removes the physical Log Databases from SQL Server|
|<i class="fal fa-forward-step" aria-hidden="true"></i> [Script B](#script-b-remove-entries-from-logtables)|Quit — report success|Quit — report failure|Removes the database records from the <span class="nodinite-product-name" title="The node that unites different systems. Or as we call it Nodinite">Nodinite</span> [Configuration Database][ConfigDB]|

<h3 id="script-a-remove-databases-from-sql-server">Script A: Remove Databases from SQL Server</h3>

``` sql
-- NOTE: @prefix, @configDB, @days, and @managedInstance MUST be identical in Script A and Script B
DECLARE @prefix          NVARCHAR(255) = 'Nodinite_Prod_Log_',  -- created by v6: 'NodiniteLog_Prod_'
        @configDB        NVARCHAR(255) = 'Nodinite_Prod_Config', -- created by v6: 'NodiniteConfig_Prod'
        @days            INT           = 180, -- Must be a positive integer
        @managedInstance BIT           = 0    -- 1 = Azure SQL Managed Instance, 0 = SQL Server

-- @dropSql contains the DROP statements that run in master context
DECLARE @dropSql  NVARCHAR(MAX) = 'USE [master]' + CHAR(13) + CHAR(10)

-- @buildSql queries LogTables in the Config DB using a 3-part name so
-- this script can safely run from any database context (e.g. master)
DECLARE @buildSql NVARCHAR(MAX) = N'
SELECT @dropSql +=
    ''EXEC msdb.dbo.sp_delete_database_backuphistory @database_name = ['' + [Database] + '']'' + CHAR(13) + CHAR(10) +
    -- SET SINGLE_USER is not supported on Azure SQL Managed Instance
    CASE WHEN @managedInstance = 0
         THEN ''ALTER DATABASE ['' + [Database] + ''] SET SINGLE_USER WITH ROLLBACK IMMEDIATE'' + CHAR(13) + CHAR(10)
         ELSE '''' END +
    ''DROP DATABASE [''  + [Database] + '']''                                                   + CHAR(13) + CHAR(10)
FROM [' + @configDB + '].[dbo].[LogTables]
WHERE  [Database]       LIKE N''' + @prefix + '%''
  AND  [EndDate]        IS NOT NULL
  AND  [EndDate]        < DATEADD(DD, ' + CAST(@days AS VARCHAR(18)) + ' * -1, GetDate())
  AND  [IsRemoteServer] = @managedInstance -- Managed Instance registers Log Databases with IsRemoteServer = 1
ORDER BY [Database]'

EXEC sp_executesql @buildSql,
     N'@dropSql NVARCHAR(MAX) OUTPUT, @managedInstance BIT',
     @dropSql OUTPUT, @managedInstance

PRINT @dropSql
-- TODO: Remove the two dashes at the start of the next line when adding to the SQL Agent job
-- EXEC sp_executesql @dropSql
```

<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>The last <code>EXEC</code> line is commented out. <strong>When testing manually</strong>, leave it commented so the script only prints what it would do. <strong>When adding this script to the SQL Agent job</strong>, remove the <code>--</code> comment prefix so the job actually performs the removal. See <a href="#step-5">Step 5</a> below.</p></div>
</aside>

<h3 id="script-b-remove-entries-from-logtables">Script B: Remove Entries from LogTables</h3>

``` sql
-- NOTE: @prefix, @configDB, @days, and @managedInstance MUST be identical in Script A and Script B
DECLARE @prefix          NVARCHAR(255) = 'Nodinite_Prod_Log_',  -- created by v6: 'NodiniteLog_Prod_'
        @configDB        NVARCHAR(255) = 'Nodinite_Prod_Config', -- created by v6: 'NodiniteConfig_Prod'
        @days            INT           = 180, -- Must be a positive integer
        @managedInstance BIT           = 0    -- 1 = Azure SQL Managed Instance, 0 = SQL Server

DECLARE @sql NVARCHAR(MAX)

SELECT @sql =
    'USE [' + @configDB + ']'                    + CHAR(13)+CHAR(10) +
    'DELETE FROM LogTables'
    + ' Where [Database] LIKE (''' + @prefix + '%'')'
    + ' AND [EndDate] IS NOT NULL'
    + ' AND [EndDate] < DATEADD(DD, ' + CAST(@days AS VARCHAR(18)) + ' * -1, GetDate())'
    + ' AND [IsRemoteServer] = ' + CAST(@managedInstance AS CHAR(1)) + CHAR(13)+CHAR(10)

PRINT @sql
-- TODO: Remove the two dashes at the start of the next line when adding to the SQL Agent job
-- EXEC sp_executesql @sql
```

<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>Same rule applies: leave the <code>EXEC</code> line commented for manual testing. Uncomment it only when adding this script to the SQL Agent job in <a href="#step-6">Step 6</a>.</p></div>
</aside>

---

## <i class="fal fa-forward-step" aria-hidden="true"></i> Step 1: Test the Scripts Manually First

Before you build the job, verify the scripts return the correct list of databases. **Skipping this step risks deleting the wrong databases.**

<aside aria-label="Warning" class="nodinite-note nodinite-note--warning">
<p class="nodinite-note__label" aria-hidden="true"><i class="far fa-fw fa-triangle-exclamation"></i> Warning</p>
<div class="nodinite-note__content"><p>If the Messages tab only shows <code>USE [master]</code> with no <code>DROP DATABASE</code> lines, the most likely causes are:</p><ul>
<li>The <code>IsRemoteServer</code> flag is incorrectly set to <code>1</code> in <span class="nodinite-product-name" title="The node that unites different systems. Or as we call it Nodinite">Nodinite</span> — even though the databases are on the same server. Fix this in the Web Client first. See <a href="#fix-incorrect-isremoteserver-flag">Fix incorrect IsRemoteServer flag</a>.</li>
<li>You run Azure SQL Managed Instance but left <code>@managedInstance = 0</code> — set it to <code>1</code> in both scripts. See <a href="#azure-sql-managed-instance">Azure SQL Managed Instance</a>.</li>
<li>Your Log Databases are genuinely on a different server — connect SSMS to that server and run the job there instead.</li>
</ul></div>
</aside>

1. Open **SQL Server Management Studio (SSMS)**
2. Connect to the SQL Server **where the job will run**:
   * If your Log Databases have `IsRemoteServer = 0`: connect to the **Config DB server**
   * If your Log Databases have `IsRemoteServer = 1`: connect to the **remote SQL Server** that hosts the Log Databases
   * If you run Azure SQL Managed Instance: connect to the **Managed Instance** and set `@managedInstance = 1`
3. Click **New Query** in the toolbar
4. Paste in **Script A** exactly as shown above (with the `EXEC` line commented out)
5. Update the four variables at the top (`@prefix`, `@configDB`, `@days`, `@managedInstance`) to match your environment
6. Press `F5` to run the query
7. Click the **Messages** tab at the bottom — you will see a list of database names that **would** be deleted and the generated `DROP DATABASE` statements

<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>Review this list carefully. Dropping a database is <strong>permanent and irreversible</strong> — there is no undo. If a database appears in the list that you want to keep, increase the <code>@days</code> value. Confirm with your team that the listed databases truly contain expired data before continuing.</p></div>
</aside>

Once you are satisfied the list is correct, repeat the test for **Script B** the same way.

---

## <i class="fal fa-forward-step" aria-hidden="true"></i> Step 2: Open SQL Server Management Studio

1. Open **SQL Server Management Studio (SSMS)**. If you do not have it, [download it here for free][SSMS Download]<sup><i class="fal fa-arrow-up-right-from-square" aria-hidden="true"></i></sup>
2. In the **Connect to Server** dialog:
   * **Server name**: the hostname or IP of the SQL Server that hosts your <span class="nodinite-product-name" title="The node that unites different systems. Or as we call it Nodinite">Nodinite</span> [Configuration Database][ConfigDB]
   * **Authentication**: use [Windows Authentication][Windows Authentication] when the server is domain-joined. Use **SQL Server Authentication** if your DBA gave you a SQL login and password
3. Click **Connect**

<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>If you are unsure of the server name, look at the SQL Server connection string of the environment in the Portal, <a href="https://docs.nodinite.com/install-and-update/getting-started/version-7/install-nodinite-v7-steps/03-infrastructure/#configure-sql-server-connectivity">Step 3: Infrastructure</a>, or contact your DBA.</p></div>
</aside>

---

## <i class="fal fa-forward-step" aria-hidden="true"></i> Step 3: Navigate to SQL Server Agent

SQL Server Agent is the built-in job scheduler in SQL Server. Think of it as Windows Task Scheduler, but built directly into SQL Server and far more reliable for database operations. [Learn more about SQL Server Agent][SQL Server Agent Docs]<sup><i class="fal fa-arrow-up-right-from-square" aria-hidden="true"></i></sup>

In the **Object Explorer** panel on the left side of SSMS:

1. Expand the tree node for your SQL Server instance
2. Scroll down until you see **SQL Server Agent**
3. Expand **SQL Server Agent**
4. Right-click **Jobs**
5. Click **New Job...**

<aside aria-label="Warning" class="nodinite-note nodinite-note--warning">
<p class="nodinite-note__label" aria-hidden="true"><i class="far fa-fw fa-triangle-exclamation"></i> Warning</p>
<div class="nodinite-note__content"><p>If <strong>SQL Server Agent</strong> is missing from the tree, either the Agent service is not running or you are connected to a SQL Server Express instance (which does not include Agent). For non-Express editions, ask your DBA to start the SQL Server Agent Windows Service. Open <strong>Services</strong> (<code>services.msc</code>), find <strong>SQL Server Agent (MSSQLSERVER)</strong> and set it to <strong>Automatic</strong> startup.</p></div>
</aside>

---

## <i class="fal fa-forward-step" aria-hidden="true"></i> Step 4: Name the Job

The **New Job** dialog opens. On the **General** tab:

1. **Name**: Enter a clear and descriptive name. Good examples:
   * `Nodinite - Remove Old Log Databases - Prod`
   * `Nodinite Log DB Cleanup (Production)`

2. **Owner**: Set this to a SQL login with **sysadmin** rights — typically `sa` or a dedicated DBA service account. **Do not use a personal login.** If your personal account is ever removed or disabled, the job will stop running silently.

   If your service account is not `sysadmin`, review [SQL Server Sysadmin Requirements][] and disable [DatabaseMaintenance][] where required.

3. **Category**: Click the `...` button and select **Database Maintenance**. This is cosmetic but makes it easy to find the job among dozens of others.

4. **Description**: Write a short note about what the job does and why. For example:
   > Removes Nodinite Log Databases older than 180 days. Configured per retention policy. Runs every Sunday at 02:00. Created by [your name] on [date].

5. Make sure the **Enabled** checkbox is ticked.

<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>A good naming convention for jobs is: <code>Product - Action - Environment</code>. For example: <code>Nodinite - Remove Old Log Databases - Prod</code>. When you have many jobs, a consistent naming convention makes maintenance much easier.</p></div>
</aside>

---

<h2 id="step-5"><i class="fal fa-forward-step" aria-hidden="true"></i> Step 5: Add Job Step A — Remove Databases</h2>

Click the **Steps** page on the left side of the New Job dialog, then click **New...**:

1. **Step name**: `Step 1 - Remove Old Log Databases from SQL Server`
2. **Type**: `Transact-SQL script (T-SQL)`
3. **Run as**: Leave as default (`SQL Server Agent Service Account`)
4. **Database**: Select `master` from the dropdown — the script uses a 3-part database name internally to read from your Config DB, so it can safely run from `master` context

5. **Command**: Paste **Script A** from [above](#script-a-remove-databases-from-sql-server). **Before clicking OK, remove the `--` comment prefix from the last `EXEC` line** so the script reads:

   ```sql
   EXEC sp_executesql @dropSql
   ```

   Also update the four variables at the top to match your environment.

6. Click the **Advanced** tab within the step dialog and set:
   * **On success action**: `Go to the next step`
   * **On failure action**: `Quit the job reporting failure`

7. Click **OK** to save the step.

<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>The <strong>On failure action</strong> setting is critical. Setting it to <em>Quit the job reporting failure</em> ensures that if the physical database removal in Step 1 fails, Step 2 will never run — preventing the situation where <span class="nodinite-product-name" title="The node that unites different systems. Or as we call it Nodinite">Nodinite</span> loses track of databases that still exist on SQL Server.</p></div>
</aside>

---

<h2 id="step-6"><i class="fal fa-forward-step" aria-hidden="true"></i> Step 6: Add Job Step B — Clean Up LogTables</h2>

Click **New...** again to add the second step:

1. **Step name**: `Step 2 - Remove Log Database entries from LogTables`
2. **Type**: `Transact-SQL script (T-SQL)`
3. **Run as**: Leave as default
4. **Database**: Select your <span class="nodinite-product-name" title="The node that unites different systems. Or as we call it Nodinite">Nodinite</span> [Configuration Database][ConfigDB] from the dropdown (e.g., `Nodinite_Prod_Config`)

5. **Command**: Paste **Script B** from [above](#script-b-remove-entries-from-logtables). **Remove the `--` comment prefix from the last `EXEC` line** so the script reads:

   ```sql
   EXEC sp_executesql @sql
   ```

   Update the four variables to match your environment — they **must be identical** to the values used in Step 1.

6. Click the **Advanced** tab and set:
   * **On success action**: `Quit the job reporting success`
   * **On failure action**: `Quit the job reporting failure`

7. Click **OK** to save the step.

<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 reorder job steps using the <strong>Move step up / Move step down</strong> arrows on the Steps page. <strong>Step 1 must always come before Step 2.</strong></p></div>
</aside>

---

## <i class="fal fa-forward-step" aria-hidden="true"></i> Step 7: Set Up a Schedule

Without a schedule, the job must be started manually every time. A recurring schedule automates the cleanup.

<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>Always pick a time when the SQL Server is under low load. Early Sunday morning (01:00–04:00) is the most common choice. Avoid business hours and integration-heavy periods. Ask your team if there is a defined maintenance window.</p></div>
</aside>

Click the **Schedules** page, then click **New...**:

1. **Name**: Give the schedule a descriptive name, for example: `Weekly Sunday 02:00`
2. **Schedule type**: `Recurring`
3. **Frequency** section:
   * **Occurs**: `Weekly`
   * **Recurs every**: `1` week(s)
   * Tick the **Sunday** checkbox (or whichever day your organization uses as a maintenance window)
4. **Daily frequency** section:
   * **Occurs once at**: `02:00:00`
5. **Duration** section:
   * **Start date**: today's date
   * **End date**: `No end date`
6. Click **OK** to save the schedule.

<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>For more scheduling options — such as running on multiple days or on the last day of the month — see <a href="https://learn.microsoft.com/en-us/ssms/agent/create-a-schedule">Create a Schedule in SQL Server Agent</a><sup><i class="fal fa-arrow-up-right-from-square" aria-hidden="true"></i></sup>.</p></div>
</aside>

---

## <i class="fal fa-forward-step" aria-hidden="true"></i> Step 8: Configure Failure Notifications (Recommended)

Getting an alert when the job **fails** lets you act before a retention problem grows.

Click the **Notifications** page:

1. Tick **E-mail**
2. Select an **operator** (an operator is a named email recipient configured in SQL Server Agent)
3. Set the condition to **When the job fails**
4. Click **OK**

<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 do not see any operators in the dropdown, or if email notifications are not yet configured, ask your DBA to set up <strong>Database Mail</strong> and create an <strong>Operator</strong>. See <a href="https://learn.microsoft.com/en-us/sql/relational-databases/database-mail/database-mail">Configure Database Mail</a><sup><i class="fal fa-arrow-up-right-from-square" aria-hidden="true"></i></sup> on Microsoft Learn. You can skip this step for now and check job history manually instead.</p></div>
</aside>

---

## <i class="fal fa-forward-step" aria-hidden="true"></i> Step 9: Save the Job

Click **OK** at the bottom of the New Job dialog to save.

The job now appears under **SQL Server Agent > Jobs** in the Object Explorer. Right-click it and select **Properties** at any time to review or change its configuration.

---

## <i class="fal fa-forward-step" aria-hidden="true"></i> Step 10: Run the Job Manually to Verify

Before relying on the scheduled run, trigger the job manually once to confirm everything works end-to-end:

1. In the **Object Explorer**, expand **SQL Server Agent > Jobs**
2. Right-click your job (e.g., `Nodinite - Remove Old Log Databases - Prod`)
3. Select **Start Job at Step...** and choose **Step 1 - Remove Old Log Databases from SQL Server**
4. Click **Start** in the dialog that appears
5. Wait for the progress indicator to complete — this is usually fast (a few seconds to a minute depending on how many databases are removed)
6. Click **Close**

---

## <i class="fal fa-forward-step" aria-hidden="true"></i> Step 11: Verify the Results

Check that the job completed successfully and that the correct databases were removed:

1. In the **Object Explorer**, right-click your job
2. Select [View History][]
3. The **Job Activity Monitor** opens — find your job in the list:
   * ✅ A green checkmark means the job succeeded
   * ❌ A red X means the job failed
4. Click on any run row to expand it and read the output messages from each step
5. Refresh the **Databases** node in the Object Explorer — the removed Log Databases should no longer appear
6. Open the <span class="nodinite-product-name" title="The node that unites different systems. Or as we call it Nodinite">Nodinite</span> [Web Client][] and navigate to **Administration > Settings > Log Databases** — deleted entries should be gone from the list

<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>Bookmark the <strong>Job Activity Monitor</strong> (right-click <strong>SQL Server Agent</strong> &gt; <strong>Monitor Job Activity</strong>). It gives you a real-time overview of all job statuses and is the fastest way to spot problems after a maintenance window.</p></div>
</aside>

---

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

* <i class="fal fa-list-check" aria-hidden="true"></i> [Microsoft SQL Server Options][Microsoft SQL Server]  
* <i class="fal fa-database" aria-hidden="true"></i> [Add or Manage a Log Database][AddOrManageLogDB]  
* <i class="fal fa-user-shield" aria-hidden="true"></i> [SQL Server Sysadmin Requirements][]  

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

* <i class="fal fa-database" aria-hidden="true"></i> [Log Databases][]  
* <i class="fal fa-key" aria-hidden="true"></i> [System Parameters][]  
* <i class="fal fa-table" aria-hidden="true"></i> [DatabaseMaintenance][]  
* <i class="fal fa-hard-drive" aria-hidden="true"></i> [Logging Service][]  
* <i class="fal fa-database" aria-hidden="true"></i> [SQL Server Troubleshooting][SQL Server Overview]  
* <i class="fal fa-link" aria-hidden="true"></i> [Linked Servers][]  

[AddOrManageLogDB]:https://docs.nodinite.com/administration/settings/log-databases/add-or-manage-log-database/
[ConfigDB]:https://docs.nodinite.com/core-services/configuration-database/overview/
[Database Mail Docs]:https://learn.microsoft.com/en-us/sql/relational-databases/database-mail/database-mail
[DatabaseMaintenance]:https://docs.nodinite.com/administration/settings/system-parameters/databasemaintenance/
[DaysToKeepMessageContextDefault]:https://docs.nodinite.com/administration/settings/system-parameters/daystokeepmessagecontextdefault/
[DaysToKeepMessageDataDefault]:https://docs.nodinite.com/administration/settings/system-parameters/daystokeepmessagedatadefault/
[DaysToKeepMessageEventsDefault]:https://docs.nodinite.com/administration/settings/system-parameters/daystokeepmessageeventsdefault/
[DaysToKeepMonitorEvents]:https://docs.nodinite.com/administration/settings/system-parameters/daystokeepmonitorevents/
[DaysToSplitDatabaseOn]:https://docs.nodinite.com/administration/settings/system-parameters/daystosplitdatabaseon/
[Linked Servers]:https://docs.nodinite.com/install-and-update/troubleshooting/sql-server/linked-servers/
[Log Databases]:https://docs.nodinite.com/core-services/log-databases/overview/
[Log Databases Admin]:https://docs.nodinite.com/administration/settings/log-databases/overview/
[Log Event]:https://docs.nodinite.com/core-services/log-event/overview/
[Logging Service]:https://docs.nodinite.com/core-services/logging-service/overview/
[Message Types]:https://docs.nodinite.com/repository-model/message-types/overview/
[Microsoft SQL Server]:https://docs.nodinite.com/install-and-update/troubleshooting/sql-server/sql-server-options/
[Portal SQL Server]:https://docs.nodinite.com/install-and-update/getting-started/version-7/install-nodinite-v7-steps/03-infrastructure/#configure-sql-server-connectivity
[Scheduled Tasks]:https://docs.nodinite.com/logging-and-monitoring/windows-server/features/scheduled-tasks/
[SizeToSplitDatabaseOn]:https://docs.nodinite.com/administration/settings/system-parameters/sizetosplitdatabaseon/
[SQL Agent Schedule Docs]:https://learn.microsoft.com/en-us/ssms/agent/create-a-schedule
[SQL Server Agent Docs]:https://learn.microsoft.com/en-us/ssms/agent/sql-server-agent
[SQL Server Express]:https://docs.nodinite.com/install-and-update/troubleshooting/sql-server/sql-server-options/#sql-server-express
[SQL Server Overview]:https://docs.nodinite.com/install-and-update/troubleshooting/sql-server/overview/
[SQL Server Sysadmin Requirements]:https://docs.nodinite.com/install-and-update/troubleshooting/sql-server/sql-server-sysadmin-requirements/
[SSMS Download]:https://learn.microsoft.com/en-us/ssms/install/install
[System Parameters]:https://docs.nodinite.com/administration/settings/system-parameters/overview/
[View History]:https://docs.nodinite.com/administration/access-management/roles/features/permission-set-for-monitor-views/
[Web Client]:https://docs.nodinite.com/getting-started/overview/
[Windows Authentication]:https://docs.nodinite.com/install-and-update/troubleshooting/sql-server/connection-strings/