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 workflow is set up and the database connection works fine, but I’m stuck on one thing.
I need the AI to create the SQL query dynamically and then use that query in the Microsoft SQL node. The problem is I can’t figure out what exactly should go in the “Query” parameter field to make this work.
I’ve been trying different approaches like leaving it empty, using {{ $fromAI('query') }}, and other variations but nothing seems to work. With Supabase, this was much easier since it didn’t need a specific query parameter.
Has anyone successfully set this up? What’s the correct syntax or approach for letting the AI populate the query field automatically?
try {{ $json.query }} if your ai node outputs the sql as a ‘query’ field. make sure the ai node comes right before the sql node in your workflow. i had the same issue - turned out to be wrong expression syntax.
Had this exact issue last month. Your AI node needs to output just the raw SQL query - no extra text or formatting. I had to tweak my AI prompt to return only the SQL statement, then used {{ $node["Previous Node"].json["output"] }} in the query field (swap “Previous Node” for your AI node’s actual name). Microsoft SQL node’s way pickier about input than other database nodes. What got me was the AI kept adding markdown code blocks or explanatory text around queries. Ended up throwing a Code node between the AI and SQL nodes to clean things up with .replace(/```sql|```/g, '').trim() - strips all that formatting junk.
The syntax depends on how your AI node outputs data. If the SQL query comes back as part of a bigger response object, try {{ $('AI_NODE_NAME').first().json.generated_sql }} - just swap AI_NODE_NAME for whatever you called your node. I’ve hit this same issue when the AI buried the query inside other fields or mixed it with text. Check your AI node’s output preview first to see exactly how it’s structured - that’ll show you the right path. Also make sure your AI is actually generating T-SQL for SQL Server, not generic SQL that works elsewhere but breaks here.