How to configure n8n for AI-generated SQL queries on Microsoft SQL database?

I’m setting up an AI-powered system to fetch data from a Microsoft SQL database using n8n. The workflow is connected to the database, but I’m stuck on how to make the AI generate SQL queries.

I’ve tried different approaches in the ‘Query’ parameter of the Microsoft SQL tool:

- Leaving it blank
- Using empty quotes: '' or ""
- Trying expressions: {{ $fromAI('') }} or {{ $fromAI('query') }}

None of these worked. I’m not sure what to put there to get the AI to create the query. It was easier with Supabase, which didn’t need this step.

Any ideas on what value should go in the ‘Query’ parameter to make this work? I feel like I’m just guessing at this point. Help would be much appreciated!

I have also experimented with integrating n8n and AI tools to generate SQL queries. In my experience, separating the query generation from the execution node helped a great deal. I set up an AI node to dynamically create the SQL syntax and then referenced its output in the Microsoft SQL node by using an expression. This method avoids hardcoding the query directly into the node and provides flexibility for various command requirements. Experimenting with prompt details in the AI node enabled me to fine-tune the resulting queries effectively.

Having worked extensively with n8n and AI-generated queries, I can offer some insights. The key is to use a dedicated AI node before your Microsoft SQL node. This AI node should be configured to output a structured JSON response containing the generated SQL query. Then, in your Microsoft SQL node, you can reference this output using an expression like {{ $node[‘AI_Query_Generator’].json[‘sql_query’] }}. This approach allows for more control over the query generation process and easier debugging. Make sure to properly sanitize and validate the AI-generated query to prevent potential SQL injection vulnerabilities. It’s also beneficial to implement error handling to manage cases where the AI generates invalid SQL syntax.

hey dancingfox, i feel ur pain! ive been there too. what worked 4 me was using a separate AI node to generate the query first. then in the MS SQL node, u can use something like {{ $node[‘AI_Node’].json[‘generated_query’] }} as the query. it’s a bit tricky at first but once u get it, it’s smooth sailing!