7 Jun 2024

How to generate log report of each table from database

 Generating a log report of each table in a SQL Server database involves creating a mechanism to track changes (inserts, updates, deletes) on each table. This can be achieved using several methods, including:

1. Change Data Capture (CDC)

CDC is a feature in SQL Server that provides an easy way to track changes. Here’s how to set it up:

Enable CDC on the Database


USE [YourDatabaseName]; GO EXEC sys.sp_cdc_enable_db; GO

Enable CDC on Each Table


USE [YourDatabaseName]; GO EXEC sys.sp_cdc_enable_table @source_schema = N'dbo', -- Replace with your schema @source_name = N'YourTableName', -- Replace with your table name @role_name = NULL; GO

Query CDC Logs

CDC creates tables with the captured changes. You can query these tables for logs:


SELECT * FROM cdc.dbo_YourTableName_CT; -- Change 'dbo' and 'YourTableName' accordingly

2. Triggers

Using triggers is another method to log changes to each table. You can create insert, update, and delete triggers to log changes into a separate log table.

Create Log Table


CREATE TABLE ChangeLog ( LogID INT IDENTITY(1,1) PRIMARY KEY, TableName NVARCHAR(255), ChangeType NVARCHAR(10), ChangeDate DATETIME DEFAULT GETDATE(), ChangedData NVARCHAR(MAX) );

Create Trigger for Insert


CREATE TRIGGER trgAfterInsert ON YourTableName AFTER INSERT AS BEGIN DECLARE @Change NVARCHAR(MAX); SELECT @Change = ( SELECT * FROM inserted FOR XML PATH(''), TYPE ).value('.', 'NVARCHAR(MAX)'); INSERT INTO ChangeLog (TableName, ChangeType, ChangedData) VALUES ('YourTableName', 'INSERT', @Change); END;

Create Trigger for Update


CREATE TRIGGER trgAfterUpdate ON YourTableName AFTER UPDATE AS BEGIN DECLARE @Change NVARCHAR(MAX); SELECT @Change = ( SELECT * FROM inserted FOR XML PATH(''), TYPE ).value('.', 'NVARCHAR(MAX)'); INSERT INTO ChangeLog (TableName, ChangeType, ChangedData) VALUES ('YourTableName', 'UPDATE', @Change); END;

Create Trigger for Delete


CREATE TRIGGER trgAfterDelete ON YourTableName AFTER DELETE AS BEGIN DECLARE @Change NVARCHAR(MAX); SELECT @Change = ( SELECT * FROM deleted FOR XML PATH(''), TYPE ).value('.', 'NVARCHAR(MAX)'); INSERT INTO ChangeLog (TableName, ChangeType, ChangedData) VALUES ('YourTableName', 'DELETE', @Change); END;

3. SQL Server Audit

SQL Server Audit is another feature that allows tracking of events at the server and database levels.

Create Server Audit


CREATE SERVER AUDIT [AuditName] TO FILE ( FILEPATH = 'C:\AuditLogs\' ); ALTER SERVER AUDIT [AuditName] WITH (STATE = ON);

Create Database Audit Specification


USE [YourDatabaseName]; GO CREATE DATABASE AUDIT SPECIFICATION [AuditSpecificationName] FOR SERVER AUDIT [AuditName] ADD (INSERT ON OBJECT::[dbo].[YourTableName] BY [public]), ADD (UPDATE ON OBJECT::[dbo].[YourTableName] BY [public]), ADD (DELETE ON OBJECT::[dbo].[YourTableName] BY [public]) WITH (STATE = ON); GO

4. SQL Server Profiler

For short-term logging, you can use SQL Server Profiler to trace activities on your database. This is more of a real-time monitoring tool and less of a long-term logging solution.

Querying the Log Report

To query the log report generated by triggers or CDC, you can use a simple SELECT statement:


SELECT * FROM ChangeLog ORDER BY ChangeDate DESC;

This will provide you with a log of changes for each table that has been configured to log changes.

By setting up any of these methods, you can effectively generate and manage log reports for each table in your database.

How to access MS Sql Database outside LAN

 Accessing an MS SQL database outside a LAN involves several steps to ensure security and proper configuration. Here’s a step-by-step guide to achieving this:

1. Prepare the SQL Server

Enable TCP/IP Protocol

  1. Open SQL Server Configuration Manager.
  2. Expand SQL Server Network Configuration and select Protocols for [Your SQL Instance].
  3. Right-click TCP/IP and select Enable.
  4. Double-click TCP/IP, go to the IP Addresses tab, and ensure the port number (default is 1433) is set.

Allow SQL Server Authentication

  1. Open SQL Server Management Studio (SSMS).
  2. Connect to your SQL Server instance.
  3. Right-click the server name in Object Explorer and select Properties.
  4. Go to the Security tab and ensure SQL Server and Windows Authentication mode is selected.

2. Configure Firewall

On the SQL Server Machine

  1. Open Windows Firewall.
  2. Go to Advanced settings and then Inbound Rules.
  3. Create a new rule allowing TCP traffic on port 1433.

On the Router (if needed)

  1. Log in to your router’s administration panel.
  2. Find the Port Forwarding section.
  3. Add a new rule to forward traffic on port 1433 to the IP address of your SQL Server machine.

3. Obtain External IP Address

Determine your network’s external IP address. You can do this by visiting a site like WhatIsMyIP.com.

4. Configure DNS (Optional)

If you prefer not to use the raw IP address, set up a dynamic DNS (DDNS) service to map a domain name to your external IP. Services like No-IP or DynDNS can be useful for this.

5. Test Connectivity

Use tools like telnet or a SQL client from an external network to test connectivity:


telnet [external IP] 1433

6. Connect Using SQL Server Management Studio

From an External Network

  1. Open SQL Server Management Studio (SSMS).
  2. In the Connect to Server dialog, enter your external IP address (or DDNS hostname) and port, formatted like xxx.xxx.xxx.xxx,1433.
  3. Use SQL Server Authentication with the username and password configured on your SQL Server.

Security Considerations

  1. Use Strong Passwords: Ensure all SQL Server accounts have strong, complex passwords.
  2. Limit IP Access: Configure firewall rules to allow only specific IP addresses or IP ranges.
  3. Use VPN: For added security, consider setting up a VPN to connect to the LAN securely, reducing the exposure of the SQL Server directly to the internet.
  4. Regular Updates and Patches: Ensure your SQL Server and Windows are updated with the latest security patches.

By following these steps, you can securely access your MS SQL database from outside your LAN.

SQL Server Copilot AI

 Here are some of the latest tips and advanced concepts for Microsoft SQL Server (MS SQL) in 2024: 1. SQL Server Copilot AI Microsoft has in...