Remove historical Log Databases
Section titled “Remove historical Log Databases”Easily automate the safe removal of historical Nodinite 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
Nodinite automatically creates new databases when the following System Parameters are met:
- DaysToSplitDatabaseOn — Create a new database after this many days.
- SizeToSplitDatabaseOn — Create a new database when exceeding this size.
Understanding Data Retention
Section titled “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 are individually removed based on the Message Type. The following System Parameters specify how long to keep events and data by default:
- DaysToKeepMessageEventsDefault
- DaysToKeepMessageContextDefault
- DaysToKeepMessageDataDefault
- DaysToKeepMonitorEvents
A Log Database 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.
created by the Logging Service"] -->|"Size or days reached"| Archive["fa:fa-box-archive Archive Log Database
EndDate set"] Archive -->|"Retention purges Log Events"| Expired["fa:fa-hourglass-end Expired
EndDate older than @days"] Expired -->|"Job step 1: Script A"| Dropped["fa:fa-trash Database dropped
on SQL Server"] Dropped -->|"Job step 2: Script B"| Clean["fa:fa-broom Row removed
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
Diagram: the life of a Log Database. 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, 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 (Script B). Red marks the safety stop when Script A fails.
What You Need Before Starting
Section titled “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
- ✅ A SQL Server login with sysadmin privileges on the server that hosts the Nodinite Configuration Database
- ✅ The SQL Server Agent service is running on that SQL Server instance (check with your DBA if unsure)
- ✅ The name of your Nodinite Configuration Database — for example,
Nodinite_Prod_Config - ✅ The prefix of your Nodinite 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.
The Scripts
Section titled “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 Nodinite. If Step 1 fails, Step 2 must never run.
Script variables
Section titled “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 Nodinite Log Database names | v7: Nodinite_Prod_Log_Created by v6: NodiniteLog_Prod_ |
@configDB |
The name of the Nodinite Configuration Database | v7: Nodinite_Prod_ConfigCreated 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 |
0 |
Local vs Remote Log Databases
Section titled “Local vs Remote Log Databases”Before using the scripts, check where your Log Databases physically reside. Run the following query on your Config DB:
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) | 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
Section titled “Azure SQL Managed Instance”On Azure SQL Managed Instance, Log Databases are registered in Nodinite 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 |
Fix Incorrect IsRemoteServer Flag
Section titled “Fix Incorrect IsRemoteServer Flag”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 Nodinite.
Fix this in the Nodinite Web Client:
- Navigate to Administration > Settings > Log Databases
- Click Edit on each affected Log Database entry
- Uncheck the Remote Server checkbox
- Click Save
- Repeat for all affected entries
Once all entries show IsRemoteServer = 0, re-run the diagnostic query above to confirm, then proceed with the scripts.
Job step execution plan
Section titled “Job step execution plan”| Job Step | On success | On failure | What it does |
|---|---|---|---|
| Script A | Go to next step | Quit — report failure | Removes the physical Log Databases from SQL Server |
| Script B | Quit — report success | Quit — report failure | Removes the database records from the Nodinite Configuration Database |
Script A: Remove Databases from SQL Server
Section titled “Script A: Remove Databases from SQL Server”-- NOTE: @prefix, @configDB, @days, and @managedInstance MUST be identical in Script A and Script BDECLARE @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 contextDECLARE @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 = 1ORDER 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 @dropSqlScript B: Remove Entries from LogTables
Section titled “Script B: Remove Entries from LogTables”-- NOTE: @prefix, @configDB, @days, and @managedInstance MUST be identical in Script A and Script BDECLARE @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 @sqlStep 1: Test the Scripts Manually First
Section titled “ 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.
- Open SQL Server Management Studio (SSMS)
- 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
- If your Log Databases have
- Click New Query in the toolbar
- Paste in Script A exactly as shown above (with the
EXECline commented out) - Update the four variables at the top (
@prefix,@configDB,@days,@managedInstance) to match your environment - Press
F5to run the query - Click the Messages tab at the bottom — you will see a list of database names that would be deleted and the generated
DROP DATABASEstatements
Once you are satisfied the list is correct, repeat the test for Script B the same way.
Step 2: Open SQL Server Management Studio
Section titled “ Step 2: Open SQL Server Management Studio”- Open SQL Server Management Studio (SSMS). If you do not have it, download it here for free
- In the Connect to Server dialog:
- Server name: the hostname or IP of the SQL Server that hosts your Nodinite Configuration Database
- Authentication: use Windows Authentication when the server is domain-joined. Use SQL Server Authentication if your DBA gave you a SQL login and password
- Click Connect
Step 3: Navigate to SQL Server Agent
Section titled “ 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
In the Object Explorer panel on the left side of SSMS:
- Expand the tree node for your SQL Server instance
- Scroll down until you see SQL Server Agent
- Expand SQL Server Agent
- Right-click Jobs
- Click New Job...
Step 4: Name the Job
Section titled “ Step 4: Name the Job”The New Job dialog opens. On the General tab:
-
Name: Enter a clear and descriptive name. Good examples:
Nodinite - Remove Old Log Databases - ProdNodinite Log DB Cleanup (Production)
-
Owner: Set this to a SQL login with sysadmin rights — typically
saor 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. -
Category: Click the
...button and select Database Maintenance. This is cosmetic but makes it easy to find the job among dozens of others. -
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].
-
Make sure the Enabled checkbox is ticked.
Step 5: Add Job Step A — Remove Databases
Section titled “ Step 5: Add Job Step A — Remove Databases”Click the Steps page on the left side of the New Job dialog, then click New...:
-
Step name:
Step 1 - Remove Old Log Databases from SQL Server -
Type:
Transact-SQL script (T-SQL) -
Run as: Leave as default (
SQL Server Agent Service Account) -
Database: Select
masterfrom the dropdown — the script uses a 3-part database name internally to read from your Config DB, so it can safely run frommastercontext -
Command: Paste Script A from above. Before clicking OK, remove the
--comment prefix from the lastEXECline so the script reads:EXEC sp_executesql @dropSqlAlso update the four variables at the top to match your environment.
-
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
- On success action:
-
Click OK to save the step.
Step 6: Add Job Step B — Clean Up LogTables
Section titled “ Step 6: Add Job Step B — Clean Up LogTables”Click New... again to add the second step:
-
Step name:
Step 2 - Remove Log Database entries from LogTables -
Type:
Transact-SQL script (T-SQL) -
Run as: Leave as default
-
Database: Select your Nodinite Configuration Database from the dropdown (e.g.,
Nodinite_Prod_Config) -
Command: Paste Script B from above. Remove the
--comment prefix from the lastEXECline so the script reads:EXEC sp_executesql @sqlUpdate the four variables to match your environment — they must be identical to the values used in Step 1.
-
Click the Advanced tab and set:
- On success action:
Quit the job reporting success - On failure action:
Quit the job reporting failure
- On success action:
-
Click OK to save the step.
Step 7: Set Up a Schedule
Section titled “ Step 7: Set Up a Schedule”Without a schedule, the job must be started manually every time. A recurring schedule automates the cleanup.
Click the Schedules page, then click New...:
- Name: Give the schedule a descriptive name, for example:
Weekly Sunday 02:00 - Schedule type:
Recurring - Frequency section:
- Occurs:
Weekly - Recurs every:
1week(s) - Tick the Sunday checkbox (or whichever day your organization uses as a maintenance window)
- Occurs:
- Daily frequency section:
- Occurs once at:
02:00:00
- Occurs once at:
- Duration section:
- Start date: today's date
- End date:
No end date
- Click OK to save the schedule.
Step 8: Configure Failure Notifications (Recommended)
Section titled “ 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:
- Tick E-mail
- Select an operator (an operator is a named email recipient configured in SQL Server Agent)
- Set the condition to When the job fails
- Click OK
Step 9: Save the Job
Section titled “ 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.
Step 10: Run the Job Manually to Verify
Section titled “ 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:
- In the Object Explorer, expand SQL Server Agent > Jobs
- Right-click your job (e.g.,
Nodinite - Remove Old Log Databases - Prod) - Select Start Job at Step... and choose Step 1 - Remove Old Log Databases from SQL Server
- Click Start in the dialog that appears
- Wait for the progress indicator to complete — this is usually fast (a few seconds to a minute depending on how many databases are removed)
- Click Close
Step 11: Verify the Results
Section titled “ Step 11: Verify the Results”Check that the job completed successfully and that the correct databases were removed:
- In the Object Explorer, right-click your job
- Select View History
- 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
- Click on any run row to expand it and read the output messages from each step
- Refresh the Databases node in the Object Explorer — the removed Log Databases should no longer appear
- Open the Nodinite Web Client and navigate to Administration > Settings > Log Databases — deleted entries should be gone from the list