Back to Blog

Try n8n free for 10 days — no charge until day 11 on select plans

Or skip the trial and start from $4/mo today

n8nMSSQLintegrationautomationdatabases

n8n + MSSQL Integration: 5 Powerful Workflows You Can Build

n8nautomation TeamSeptember 10, 2026
Managing enterprise data often requires bridging legacy database systems with modern cloud services. When you integrate MSSQL with n8n, you gain the ability to orchestrate workflows that move data bi-directionally between Microsoft SQL Server and over 400 integrations. Writing custom cron scripts to poll database changes or manually executing ETL pipelines is slow and prone to errors. Using n8n allows you to process thousands of database rows, trigger actions based on table updates, and feed structured database outputs directly into modern APIs. By hosting your instances on a managed service like n8nautomation.cloud, you secure dependable 24/7 uptime and automated backups without managing complex server infrastructure.

How to Connect MSSQL to n8n

Establishing a connection between Microsoft SQL Server and your n8n workflow requires configuring both your database server permissions and your n8n credentials correctly. Because n8n often runs within Linux-based container environments, authenticating via standard SQL Server logins is far more reliable than attempting complex Windows Active Directory domain authentication.

  1. Configure SQL Server and Gather Credentials: Open SQL Server Management Studio (SSMS) and connect to your database engine. Ensure "SQL Server and Windows Authentication mode" is active under Server Properties > Security. Navigate to Security > Logins, create a dedicated login, set a strong password, and map the user to your target database. Assign the user the db_datareader role for read-only workflows, or add db_datawriter if the workflows need to insert, update, or upsert records. Ensure TCP/IP protocol is enabled in the SQL Server Configuration Manager, and that port 1433 is open through your network firewalls.
  2. Create the Microsoft SQL Credential in n8n: Log into your n8n workspace, navigate to "Credentials" in the left sidebar, and click "Add Credential". Search for "Microsoft SQL" and select it. Enter the Host IP address or domain name, Port (default is 1433), Database Name, User, and Password. If your database resides behind a secure corporate network, toggle the SSL/TLS configuration options to match your server's security requirements. Click "Save" to register the credentials.
  3. Add and Configure the MSSQL Node: Drag the Microsoft SQL node onto your workflow canvas. Select the credential you just saved. In the node settings, choose your desired Operation, such as "Execute Query", "Insert", "Update", or "Upsert". If you select "Execute Query", you can write raw T-SQL statements directly into the Query field, using dynamic expressions to inject data from preceding nodes.

Workflow 1: Synchronizing MSSQL Customer Records with Salesforce CRM

Many enterprise sales teams use cloud CRMs like Salesforce, while the fulfillment, invoicing, and legacy operational data remains locked inside an on-premise MSSQL server. Manually export-importing records or relying on nightly batch uploads creates data silos and delayed sales pipelines. This workflow synchronizes updated or newly created customer profiles directly into your CRM.

How It Works

The workflow uses a Schedule Trigger node to execute at regular intervals, such as every hour. The Microsoft SQL node then queries the database for any records updated since the last execution time. The returned rows pass through an n8n Edit Fields node to map column names to Salesforce fields. Finally, the Salesforce node updates existing contacts based on their email address or creates new records if no matching profile exists.

Real-World Example

To pull newly modified contacts, configure the Microsoft SQL node to execute a T-SQL query that checks a tracking column:

SELECT CustomerID, FirstName, LastName, Email, CompanyName, LastModifiedDate 
FROM dbo.Customers 
WHERE LastModifiedDate > :last_sync_time;

To make this dynamic, use an n8n expression to replace :last_sync_time with the previous execution timestamp:

{{ $prevRun.time.toFormat('yyyy-MM-dd HH:mm:ss') }}

The output is a JSON array of modified customers. The Edit Fields node maps CompanyName to Company and Email to Email. The Salesforce node utilizes the "Upsert" operation, matching on the email field. This ensures that any change made in the local database propagates to the CRM within the hour.

Pro Tips

To prevent infinite synchronization loops and optimize execution times, write the unique Salesforce ID back to your SQL database. Add a secondary Microsoft SQL node immediately after the Salesforce step. Configure it to run an UPDATE statement that writes the returned Salesforce Contact ID into a dedicated Salesforce_ID_Mapping column in your dbo.Customers table. On subsequent runs, you can filter out records that already possess an active mapping, cutting database load significantly.

Workflow 2: Triggering Real-Time Slack Alerts for High-Value Order Entries

For key business operations, knowing about significant transactions immediately is vital. Instead of forcing sales managers to refresh dashboards or search through financial systems, you can trigger instant chat alerts the moment a major deal or high-value purchase hits your database.

How It Works

A Schedule Trigger runs every five minutes to query the SQL Server database. The query scans the order tables for transaction amounts that exceed a specified limit. If records are returned, an If node checks the payload. If the array is populated, the workflow converts the raw row data into a formatted markdown notification and posts it to a designated Slack channel.

Tip: Always use UTC timestamps in your SQL queries. Databases configured with local timezone offsets can cause missed records or duplicate alerts when queried by servers running in different cloud zones. Standardizing on GETUTCDATE() in SQL and ISO UTC strings in n8n prevents time-gap issues.

Real-World Example

The workflow targets the dbo.Orders table. The Microsoft SQL node executes the following query:

SELECT OrderID, CustomerName, OrderTotal, CreatedAt 
FROM dbo.Orders 
WHERE OrderTotal >= 10000 
AND CreatedAt > DATEADD(minute, -5, GETUTCDATE());

If no orders exceed $10,000 within that five-minute window, the query returns an empty array, and the workflow stops executing. When a high-value order is returned, the Slack node builds a message block using the returned JSON values:

🚨 *New High-Value Order Alert!*
• *Order ID:* {{ $json.OrderID }}
• *Customer:* {{ $json.CustomerName }}
• *Total Value:* ${{ $json.OrderTotal.toFixed(2) }}
• *Processed At:* {{ $json.CreatedAt }}

The alert reaches your sales team instantly, giving them immediate visibility into key customer acquisitions.

Workflow 3: Automated PDF Invoice Generation and Email Delivery from MSSQL Data

Many businesses still draft invoices manually or use isolated billing systems that do not talk to their central database. Automating invoice generation directly from transactional SQL tables ensures invoicing accuracy, accelerates billing cycles, and reduces administrative overhead.

How It Works

This workflow runs every morning, selecting all orders marked as "Ready to Invoice". The MSSQL node executes a join query to gather customer information and order line items. A Code node parses the flat row data into a structured nested JSON object (one order with an array of items). The data is then merged into an HTML template, converted to a PDF document, and emailed to the client via Outlook or Gmail. An SQL update query then marks the orders as invoiced.

Real-World Example

The primary query retrieves order data linked with customer contact records:

SELECT o.OrderID, o.OrderDate, c.CustomerEmail, c.CustomerName, 
       i.ItemName, i.Quantity, i.UnitPrice, (i.Quantity * i.UnitPrice) AS LineTotal
FROM dbo.Orders o WITH (NOLOCK)
JOIN dbo.Customers c ON o.CustomerID = c.CustomerID
JOIN dbo.OrderItems i ON o.OrderID = i.OrderID
WHERE o.BillingStatus = 'Pending';

Because SQL joins return flat tables with redundant customer rows for each line item, the workflow utilizes an n8n Code node. The JavaScript code groups the items by OrderID, producing a structured hierarchical format:

const groupedOrders = {};
for (const item of inputData) {
  const id = item.json.OrderID;
  if (!groupedOrders[id]) {
    groupedOrders[id] = {
      OrderID: id,
      CustomerName: item.json.CustomerName,
      CustomerEmail: item.json.CustomerEmail,
      OrderDate: item.json.OrderDate,
      Items: []
    };
  }
  groupedOrders[id].Items.push({
    ItemName: item.json.ItemName,
    Quantity: item.json.Quantity,
    UnitPrice: item.json.UnitPrice,
    LineTotal: item.json.LineTotal
  });
}
return Object.values(groupedOrders).map(order => ({ json: order }));

An HTTP Request node routes the HTML string to a PDF rendering engine (such as Gotenberg). The returned binary PDF is passed directly to an email delivery node, which attaches the document and mails it to the client.

Pro Tips

Querying large transaction tables with joins can lock database tables, slowing down client applications. Always use the WITH (NOLOCK) hint on read-only queries targeting high-frequency operational tables. This permits dirty reads, preventing database blocks during busy operational hours and ensuring your workflows do not interfere with your core ERP application performance.

Workflow 4: Inventory Level Reconciliation Between MSSQL and Shopify

E-commerce operations rely on matching digital stock levels with physical warehouse numbers. If physical inventory changes are updated in a central ERP system backed by an on-premise MSSQL server, failing to replicate those updates to your online storefront leads to overselling and canceled customer orders.

How It Works

This synchronization workflow runs on a daily schedule. First, the Microsoft SQL node pulls stock levels and product SKUs from your warehouse management table. Second, the inventory list passes to an n8n Split In Batches node to handle updates sequentially. Third, the Shopify node matches the database SKU against the Shopify product variant, compares the physical quantity with the online quantity, and updates the online inventory level if there is a difference.

Note: Ensure your inventory query handles NULL values gracefully. An unexpected NULL field in the stock quantity can break downstream mapping nodes and halt your Shopify sync. Use ISNULL(StockCount, 0) to guarantee clean numerical values.

By comparing quantities inside n8n before pushing updates, you avoid making redundant API calls to Shopify. This protects your Shopify API rate limits and speeds up the reconciliation cycle. Finally, the workflow executes a write-back query to update the local database with a timestamp of the last successful sync, maintaining a clear audit trail for database administrators.

Workflow 5: Querying Database Records via Natural Language with an AI Agent

Writing SQL queries is simple for developers, but business stakeholders often need rapid insights without submitting support tickets. By pairing an n8n AI Agent with an MSSQL database connection, you can create interactive bots that answer complex inventory or sales questions instantly.

How It Works

The workflow triggers when an employee asks a question in Slack or Teams. The message is forwarded to an n8n AI Agent node equipped with a chat model and a custom SQL execution tool. The AI analyzes the user's natural language request, inspects the table schema exposed to its toolset, drafts a valid read-only T-SQL query, executes the query through the Microsoft SQL node, parses the JSON response, and posts a conversational summary back to the user.

Real-World Example

A sales manager posts a question in a dedicated Slack channel: "What were our top 3 selling products last month?" The Slack trigger forwards this prompt to the AI Agent. The agent accesses a custom tool named RunReadOnlyQuery, which is bound to your Microsoft SQL node. The agent reads the available schemas for dbo.Products and dbo.Sales, and generates the following query:

SELECT TOP 3 p.ProductName, SUM(s.Quantity) AS TotalSold 
FROM dbo.Sales s 
JOIN dbo.Products p ON s.ProductID = p.ProductID 
WHERE s.SaleDate BETWEEN '2026-08-01' AND '2026-08-31' 
GROUP BY p.ProductName 
ORDER BY TotalSold DESC;

The query executes securely, returning raw JSON data to the AI. The agent interprets the numbers and responds in Slack: "During August 2026, our top 3 selling items were: 1. Widget A (1,240 units), 2. Gadget B (980 units), and 3. Adapter C (720 units)." This allows non-technical staff to extract real-time data securely without requiring human intervention.

Why Use n8nautomation.cloud for MSSQL Workflows?

Running enterprise-level database integrations requires hosting that is reliable, secure, and isolated from other users' resource-heavy workloads. Standard cloud environments often impose rigid execution limits, cutting off database queries that process thousands of rows or timing out during complex HTML-to-PDF invoice operations. This is why hosting your integration infrastructure on a dedicated service like n8nautomation.cloud makes perfect sense.

Starting at just $4/month, you receive a dedicated, managed n8n instance running the open-source Community Edition, which supports over 400 integrations and custom community nodes. Key operational features include:

  • Zero Server Management: Focus entirely on designing database workflows while the platform handles configurations, system patches, and operational health.
  • Automatic Backups: Protect your critical workflows and database connection credentials from accidental loss with system-wide automatic backups.
  • Change Domains Anytime: Point your instance to a custom subdomain or mapping of your choice at any time from your account dashboard.
  • Live Logs Viewer: Debug complex SQL queries, connection timeouts, and payload structures in real time with our advanced dashboard log viewer.
  • Instant Migration Tool: Move existing workflows from self-hosted or legacy instances within seconds. Enter your server URL and API key, and our tool migrates workflows safely, keeping credential handshakes separate for strict security compliance.

By shifting your database operations to a dedicated managed instance, you protect corporate systems from execution bottlenecks. Sign up for a dedicated instance on our pricing page today and automate your enterprise database workflows.

Ready to automate with n8n?

Get affordable managed n8n hosting with 24/7 support.