I’m working on an n8n workflow where I want an AI agent to automatically generate SQL queries for my Microsoft SQL Server database. The database connection is working fine, but I’m stuck on what exactly should go in the Query parameter field.
Basically, I need the AI to create the SQL statement dynamically and feed it to the MS SQL node. I’ve looked through docs but can’t find clear examples of the correct syntax.
I’ve tested different approaches like leaving it empty, using {{ $fromAI('sqlQuery') }}, and {{ $fromAI('database_query') }} but nothing seems to work properly.
For context, I got this working with a Supabase setup before where no manual query parameter was needed. Just wondering if anyone knows the right way to handle this with Microsoft SQL in n8n.
The problem’s probably your expression syntax. The Microsoft SQL node needs a proper expression in the Query field that resolves to a string. Don’t use $fromAI() - that’s not standard n8n syntax. Instead, reference your AI node’s actual output like {{ $('YourAINodeName').first().json.response }}. Just swap ‘response’ for whatever field has your SQL query. I’ve hit this same issue when the AI wraps SQL in quotes or adds escape characters. Try cleaning it up with: {{ $('AINode').first().json.sqlQuery.replace(/["\]/g, '') }}. Also check if your AI’s generating SQL Server syntax instead of generic SQL. Supabase is way more forgiving since it uses PostgreSQL dialect.
Had the same problem a few months ago with an automated reporting workflow. You need to reference your AI output correctly in the Query field. Try {{ $json.sqlQuery }} if your AI node outputs SQL as a property called sqlQuery, or {{ $('AI_Node_Name').first().json.query }} - just swap AI_Node_Name for your actual node name. The syntax changes based on how your AI node structures its output. I threw a Code node between the AI and SQL nodes to clean up the query string and fix formatting issues. Also make sure your AI’s generating valid T-SQL syntax - SQL Server’s picky about PostgreSQL or MySQL patterns that work fine elsewhere.
You’re experiencing difficulties integrating an AI agent to generate SQL queries within your n8n workflow for a Microsoft SQL Server database. The database connection itself is functioning correctly, but the SQL query generated by the AI isn’t being properly passed to the MS SQL node. You’ve tried various approaches using expressions within the Query parameter field, but none have yielded the expected results. Your previous success with Supabase, which required no manual query parameter, highlights the specific challenge posed by the Microsoft SQL Server integration in n8n.
Understanding the “Why” (The Root Cause):
The issue stems from the way n8n handles expressions and the specific requirements of the Microsoft SQL node. Unlike Supabase, which might implicitly handle query execution, the MS SQL node in n8n explicitly expects a valid SQL query string as input. Incorrectly formatted or improperly passed expressions in the Query parameter field will prevent the node from executing the AI-generated query correctly. The {{ $fromAI('sqlQuery') }} or similar expressions, while seemingly logical, might not be directly interpreted correctly depending on how your AI node delivers the SQL statement. It’s critical to ensure the output from your AI node is a clean SQL string, without any extra formatting or enclosing characters that would interfere with the MS SQL node’s execution.
Step-by-Step Guide:
Verify AI Node Output: The first step is to inspect the output of your AI node. Add a Debug node immediately after your AI node. Configure the Debug node to output the entire JSON response ({{ $json }}). Run your workflow and examine the Debug node’s output to determine the exact structure and content of the AI-generated SQL query. Identify the specific property containing your SQL query (it may be called sqlQuery, query, sql_statement, or something similar). Note that the output may contain unwanted characters or be wrapped in unnecessary layers of JSON.
Extract and Clean the SQL Query: Add a Set node after the Debug node. In this Set node, extract the SQL query from your AI node’s output using the correct property name you identified in Step 1. For example, if your AI node’s output property is sqlQuery, use the expression {{ $json.sqlQuery }} to extract the SQL. However, your AI-generated query might contain extra characters (such as quotes or backslashes) that could break SQL execution. To mitigate this, use a function node (Javascript) after the Set Node. This function will clean any extra quote characters that may be introduced by the AI. For instance:
// Assuming sqlQuery is your property that holds the AI-generated query.
let cleanedQuery = $json.sqlQuery.replace(/[\"\\]/g, '');
return {
cleanedQuery: cleanedQuery
};
Connect to the Microsoft SQL Node: Now, connect the cleaned query to the MS SQL node. In the Query field of the MS SQL node, use the correct expression to reference the cleaned query. Based on the function above, it should be: {{ $json.cleanedQuery }}. Ensure that the expression is correctly pointing to the property containing the clean SQL statement from your Set Node.
Test Your Workflow: Save and execute your n8n workflow. Verify that the MS SQL node successfully executes the AI-generated SQL query. Check the output of the MS SQL node to confirm that the query result is as expected.
Common Pitfalls & What to Check Next:
AI Model Output: The format of your AI’s response is crucial. Make sure the AI is generating valid T-SQL (Transact-SQL) syntax, not generic SQL that might not be compatible with SQL Server. Examine the Debug node output carefully; the AI might be returning more than just the SQL query—it might include additional metadata. You’ll need to precisely target the part of the JSON containing only the raw SQL.
Error Handling: Implement error handling in your n8n workflow to gracefully handle cases where the AI generates invalid SQL or the database query fails. This will make debugging much easier and prevent your workflow from crashing unexpectedly.
Database Permissions: Confirm that the n8n user has the necessary permissions to execute queries on your Microsoft SQL Server database.
Alternative approaches: If the issue persists, consider using a different approach to pass the SQL query, such as building the complete SQL command string using the n8n expression editor directly within the MS SQL node.
Still running into issues? Share your (sanitized) config files, the exact command you ran, and any other relevant details. The community is here to help!
First, check if your AI node is actually spitting out the SQL query correctly. Drop a debug node right after the AI and use {{ $json }} to see what you’re really getting. You probably need something like {{ $('AI_Node').item.json.query }} or whatever property holds your SQL. The Microsoft SQL node wants plain text SQL - if your AI wraps it in JSON or adds extra stuff, it’ll break. I always throw a Set node after the AI to pull out just the query string and stick it in a clean variable like sqlStatement. Then use {{ $json.sqlStatement }} in the SQL node. Oh, and heads up - some AI models wrap SQL in markdown code blocks. You might need to strip those backticks before feeding it to the database.
Those syntax issues are classic n8n headaches. I’ve fought the same battles with AI-to-database workflows - the expression handling is always a mess.
Try {{ $('your_ai_node_name').first().json.sqlQuery }} in the Query field. Swap ‘your_ai_node_name’ for whatever you called your AI node, and ‘sqlQuery’ for the actual property with your SQL.
But after getting burned by these expression nightmares in production, I jumped to Latenode for AI database stuff.
Night and day difference. Latenode handles AI-generated SQL without the guessing games. Nodes connect cleaner, data flow’s way more reliable.
I moved a bunch of workflows where AI builds reports from SQL Server. Same results, but Latenode shows you the data structure between nodes - you know exactly what you’re dealing with.
The AI integrations work with database connectors out of the box. No more wondering if your expression broke everything.
Saved me 20+ hours of debugging across projects. The visual interface makes it obvious when AI output doesn’t match what the SQL node wants.
check your ai node output first - sometimes it returns nested json instead of plain text. i use {{ $('previous_node').first().json.sqlQuery }} but swap ‘previous_node’ for whatever you named your ai node. if that doesn’t work, throw a function node before the sql node to pull out just the query string. fixed it for me when chatgpt kept adding extra formatting that broke sql execution.