I’m working on an n8n workflow to create an AI assistant for querying a Microsoft SQL database. The connection to the database is set up, but I’m stuck on how to make the AI generate the SQL query.
In the Microsoft SQL tool, there’s a ‘Query’ parameter that I need to configure. I’ve tried various inputs like leaving it blank, using empty quotes, and even attempting {{ $fromAI('query') }}, but nothing seems to work.
For context, I’ve successfully set up a similar agent with Supabase, which doesn’t require passing a query parameter.
Has anyone figured out the correct syntax or approach for this? I’m really hoping to avoid manually writing queries and let the AI handle it. Any tips or examples would be super helpful!
hey mike, i’ve been there too! try using a code node before the MS SQL node. in the code node, use n8n’s ai functions to generate ur query and store it in a variable. then in the MS SQL node, reference that variable like {{ $node[‘Code’].json[‘aiQuery’] }}. hope that helps!
I’ve actually implemented something similar in my work with n8n and AI-generated queries for MS SQL. Here’s what worked for me:
Set up an AI Integration node (like OpenAI) before your MS SQL node. Configure it to generate the SQL query based on your input parameters.
Then, in the MS SQL node, use this expression in the Query field:
{{ $node[‘AI_Integration’].json[‘output’] }}
Replace ‘AI_Integration’ with whatever you named your AI node.
This approach lets the AI dynamically generate queries without manual intervention. Just make sure to sanitize the AI output and implement error handling to catch any potential issues with the generated SQL.
Also, consider adding a Switch node after the AI to validate the query structure before passing it to MS SQL. This extra step can save you from potential security risks or execution errors.
I have encountered this challenge before when working with n8n and AI-generated SQL queries for Microsoft SQL. One effective solution is to set up a Function node that calls your AI service to generate the SQL statement. After obtaining the query, store it in an output variable and then reference it in the Query field of the Microsoft SQL node using an expression such as {{ $node[‘Function’].json[‘generatedQuery’] }}. In my experience, this method minimizes manual input while ensuring dynamic query execution. It is important to validate the AI output to prevent execution errors.