Skip to main content

Text-to-SQL in C# with ASP.NET Core and SQL Server

Updated 18 min readMarkdown

Text-to-SQL turns a question in plain English into a SQL query, runs it, and returns the rows. This guide builds Text-to-SQL in C# with ASP.NET Core against SQL Server, using a local model through Microsoft.Extensions.AI, and shows what each step bought on a 32-question benchmark.

The same local model, qwen2.5-coder:7b, answering the same 32 questions against the same SQL Server database, three times:

Pipeline Correct Silently wrong Failed Unsafe SQL sent to the database
Table names + question → run whatever comes back 17/32 (53%) 7 8 2 (an UPDATE and a DROP TABLE)
+ schema-aware prompt 26/32 (81%) 4 2 0
+ parser validation, cost check, repair loop 28/32 (88%) 4 0 0

The model never changed. Everything that moved the score is ordinary ASP.NET Core and SQL Server engineering. This guide builds an /api/ask endpoint that takes a question in English and returns the SQL, a one-line explanation and the rows, without ever giving the model a way to damage the database.

The code is condensed from the AI Database Agent project. The full source, with 160 tests and the benchmark, is on GitHub: AfzaalLucky/ai-database-agent.

What you need: .NET 8 or later (the project runs on .NET 10), a SQL Server database where you can create a role and a user, and Ollama with qwen2.5-coder:7b pulled. The model sits behind IChatClient, so a hosted model works too (see Step 5).

This guide vs the series. This page is the build. The AI Database Agent series is the case study behind it, one article per version with what failed and why, starting from the naïve baseline in Part 1. The project page collects the results of every version.

The pipeline

question
  → build prompt (schema as DDL + rules + examples)
  → model (IChatClient → Ollama)
  → parse reply (SQL | CANNOT_ANSWER)
  → validate (ScriptDom parse + allow-list)      ─┐
  → estimate cost (SET SHOWPLAN_XML ON)           ├─ on error: send it back to the model, max 2 rounds
  → execute as agent_reader (row cap, timeout)   ─┘
  → rows
dotnet add package Microsoft.Data.SqlClient
dotnet add package Microsoft.Extensions.AI
dotnet add package OllamaSharp
dotnet add package Microsoft.SqlServer.TransactSql.ScriptDom

Step 1: A database user that can't do damage

Model-generated SQL is untrusted input. Before writing a line of C#, make it impossible for that input to do anything but read:

CREATE ROLE agent_readers AUTHORIZATION dbo;

GRANT SELECT ON SCHEMA::sales     TO agent_readers;
GRANT SELECT ON SCHEMA::catalog   TO agent_readers;
GRANT SELECT ON SCHEMA::inventory TO agent_readers;
GRANT SELECT ON hr.Departments       TO agent_readers;
GRANT SELECT ON hr.EmployeeDirectory TO agent_readers;  -- a view of hr.Employees without Salary
DENY  SELECT ON hr.Employees         TO agent_readers;
GRANT SHOWPLAN TO agent_readers;                         -- for the cost check in step 8

CREATE USER agent_reader WITHOUT LOGIN WITH DEFAULT_SCHEMA = sales;
ALTER ROLE agent_readers ADD MEMBER agent_reader;

WITHOUT LOGIN means nobody can connect as agent_reader. The API connects with its own login, which needs only CONNECT, VIEW DEFINITION and IMPERSONATE on this user, and switches identity per query.

Hide sensitive columns with a view, not a column-level DENY. A DENY on Salary alone makes a plain SELECT COUNT(*) FROM hr.Employees fail with error 230, which breaks ordinary questions. The view keeps the column out of both the permissions and the schema the model sees.

This is what stopped the naïve baseline from doing harm: its UPDATE and DROP TABLE reached the database and were refused with errors 229 and 3701. The database user is the last line of defence, not the only one. For every layer between the model and the data, see how to prevent SQL injection in LLM-generated SQL.

Step 2: Run every query as that user

internal sealed class ImpersonatedSession : IAsyncDisposable
{
    private readonly byte[] _cookie;
    public SqlConnection Connection { get; }

    private ImpersonatedSession(SqlConnection connection, byte[] cookie)
    {
        Connection = connection;
        _cookie = cookie;
    }

    public static async Task<ImpersonatedSession> OpenAsync(
        string connectionString, string agentUser, CancellationToken ct)
    {
        var connection = new SqlConnection(connectionString);
        try
        {
            await connection.OpenAsync(ct);
            await using var cmd = connection.CreateCommand();
            // Ad hoc batch on purpose: WITH COOKIE fails inside sp_executesql (error 15590).
            // agentUser comes from configuration and is validated as a simple identifier.
            cmd.CommandText = $"""
                DECLARE @cookie varbinary(8000);
                EXECUTE AS USER = N'{agentUser}' WITH COOKIE INTO @cookie;
                SELECT @cookie;
                """;
            var cookie = await cmd.ExecuteScalarAsync(ct) as byte[]
                ?? throw new InvalidOperationException("EXECUTE AS did not return a cookie.");
            return new ImpersonatedSession(connection, cookie);
        }
        catch
        {
            await connection.DisposeAsync();
            throw;
        }
    }

    public async ValueTask DisposeAsync()
    {
        try
        {
            if (Connection.State == ConnectionState.Open)
            {
                await using var cmd = Connection.CreateCommand();
                cmd.CommandText = $"REVERT WITH COOKIE = 0x{Convert.ToHexString(_cookie)};";
                await cmd.ExecuteNonQueryAsync();
            }
        }
        catch (Exception ex) when (ex is SqlException or InvalidOperationException)
        {
            SqlConnection.ClearPool(Connection); // never hand a still-impersonated connection back to the pool
        }
        finally
        {
            await Connection.DisposeAsync();
        }
    }
}

Two details carry the weight. The cookie: EXECUTE AS ... WITH COOKIE means generated SQL can't REVERT its way back to the API's identity, because only code holding the cookie can. Pooling: a pooled connection that's still impersonating would hand agent_reader (or a half-reverted state) to the next request, so a failed revert clears the pool.

Execution then adds a row cap (500 in the project) and a 15-second timeout: read with cmd.ExecuteReaderAsync, stop at maxRows, call cmd.Cancel() so the server stops producing unread rows, and return truncated: true. On a busy production database, consider pointing this connection at a readable secondary or reporting copy, so an expensive generated query never competes with transactional work.

Step 3: Give the model the schema it would need to write the query by hand

The naïve prompt sent only table and column names, about 300 tokens, and the model guessed the rest: LIMIT 1 instead of TOP (1), a Salary column that doesn't exist, and a discount column treated as a fraction when it stores 0-50, which turned discounted line totals negative.

Read the real schema from the catalog views (sys.columns, sys.indexes, sys.foreign_keys, sys.check_constraints, and the MS_Description extended properties) and send it as annotated DDL, the format code models have seen most. CHECK constraints give you the allowed values of status columns. Then read visibility while impersonating agent_reader, and drop anything it can't select. The model should see exactly what the agent may query, so hr.Employees never appears, and neither does Salary. Rendered, a table looks like this:

-- Sales orders (header).
TABLE sales.Orders (
  OrderId int PRIMARY KEY,
  CustomerId int NOT NULL -> sales.Customers.CustomerId,
  OrderDate datetime2 NOT NULL,
  Status varchar(10) NOT NULL -- values: 'Pending', 'Shipped', 'Delivered', 'Cancelled', 'Returned'
)

Types, keys, join paths as -> arrows, descriptions and enum values in one compact block. Cache it: the project re-reads the catalog every 10 minutes, not per request. Part 2 of the series covers this change on its own: what the schema-aware prompt fixed, and what it couldn't.

Step 4: Write the prompt, and give the model a way out

The system prompt carries the dialect rules and one instruction most demos leave out: permission to decline.

public const string SystemPrompt = """
    You are an expert Microsoft SQL Server developer. You write one read-only T-SQL query that answers
    the user's question using ONLY the tables and columns in the schema provided.

    Rules:
    - T-SQL only: use TOP (n), never LIMIT; use GETDATE(), DATEADD, DATEDIFF, DATEFROMPARTS, EOMONTH.
    - Always write schema-qualified table names (e.g. sales.Orders) and give tables short aliases.
    - Join only along the foreign keys shown (the "->" arrows). Never guess a column that is not listed.
    - For enum-like columns, compare only with the listed values, spelled exactly.
    - Read the descriptions: they define business meaning (for example how revenue is calculated).
    - One SELECT statement (common table expressions allowed). Never modify data.
    - If the question needs data that is not in the schema, or asks to change data, do not write a query:
      reply with exactly: CANNOT_ANSWER: <one short reason>

    Reply format: one short sentence saying what the query returns, then the query in a ```sql block.
    """;

After the schema, add what the schema can't say: today's date (so "last month" means something), the currency, and business rules such as revenue excluding cancelled and returned orders. Without that rule the baseline reported January revenue as 498,209.57 instead of 469,328.68, a number that looks fine and is wrong.

Then add a few worked examples as prior chat turns (ChatRole.User question, ChatRole.Assistant explanation plus a ```sql block). The model imitates the examples exactly, including the sentence before the SQL, so write a real explanation. An example with "Here is the query." gets that sentence copied into every answer.

Step 5: Call the model through IChatClient

Microsoft.Extensions.AI keeps the pipeline provider-agnostic. If you haven't set up a local model yet, first run Ollama locally with .NET: that guide covers installation, model choice and the settings behind both comments below.

builder.Services.AddChatClient(sp =>
    {
        // 127.0.0.1, not localhost: on Windows localhost resolves to ::1 first and Ollama listens
        // on IPv4 only, so every new connection waited ~2 s for the IPv6 attempt to fail.
        var http = new HttpClient
        {
            BaseAddress = new Uri("http://127.0.0.1:11434"),
            Timeout = TimeSpan.FromSeconds(180), // the first call also loads the model
        };
        return new OllamaApiClient(http, "qwen2.5-coder:7b");
    })
    .Use(inner => new ConfigureOptionsChatClient(inner,
        // Ollama's default context was too small for a schema-aware prompt.
        o => o.AddOllamaOption(OllamaOption.NumCtx, 8192)))
    .UseLogging();

Both comments are real findings. The context-window one is the nastier: Ollama truncates the prompt without an error, so the model silently loses the start of your schema. Newer Ollama versions pick the default context from available GPU memory, but a schema-aware prompt can still outgrow it, so set NumCtx explicitly.

Swapping to OpenAI or Claude later means changing this registration, not the pipeline. With Microsoft.Extensions.AI.OpenAI, use new OpenAI.Chat.ChatClient(model, apiKey).AsIChatClient(), and drop the NumCtx option because it's Ollama-specific. For Azure OpenAI, create an AzureOpenAIClient, then .GetChatClient(deploymentName).AsIChatClient(). A hosted model receives the schema (including column descriptions), the question and any validation errors. In this pipeline it never sees the rows, but the schema alone may need sign-off. And every number here comes from qwen2.5-coder:7b, so re-run your own benchmark after any model change.

Step 6: Parse the reply

Small local models don't always follow the format: they drop the fence, drop the language tag, or wrap the SQL in prose. Parse defensively with three cases: a CANNOT_ANSWER: <reason> refusal (when no fenced block is present), a fenced ```sql block (trim and strip the trailing ;, and keep the rest as the explanation), and, with no fence, everything from the first line that starts with WITH or SELECT. Return (Sql, Explanation, CannotAnswerReason).

With the schema-aware prompt and this parser, the benchmark went from 53% to 81%. What remained were failures the prompt can't prevent: invented columns, columns taken from the wrong table, the occasional query that doesn't compile.

Step 7: Validate the SQL with a real T-SQL parser

Regex checks for DROP or DELETE are trivially bypassed and reject harmless queries. Microsoft ships the parser SQL Server tooling uses, ScriptDom. Parse, require exactly one SELECT, then walk the tree with an allow-list:

public static IReadOnlyList<string> Validate(string sql, IReadOnlySet<string> allowedTables)
{
    var parser = new TSql170Parser(initialQuotedIdentifiers: true);
    var fragment = parser.Parse(new StringReader(sql), out var errors);
    if (errors.Count > 0)
        return errors.Take(3).Select(e => $"Syntax error at line {e.Line}, column {e.Column}: {e.Message}").ToList();

    var statements = ((TSqlScript)fragment).Batches.SelectMany(b => b.Statements).ToList();
    if (statements is not [SelectStatement select])
        return ["Exactly one SELECT statement is allowed."];
    if (select.Into is not null)
        return ["SELECT ... INTO creates a table and is not allowed."];

    var visitor = new AllowListVisitor(allowedTables);
    select.Accept(visitor);
    return visitor.Problems;
}

// Inside AllowListVisitor : TSqlFragmentVisitor
public override void Visit(TableReference node)
{
    if (node is not (NamedTableReference or QueryDerivedTable or JoinTableReference or JoinParenthesisTableReference))
        Problems.Add($"Not allowed: table source {node.GetType().Name}."); // OPENROWSET, OPENQUERY, TVFs
}

public override void Visit(NamedTableReference node)
{
    var name = node.SchemaObject;
    if (name.ServerIdentifier is not null || name.DatabaseIdentifier is not null)
    {
        Problems.Add("Not allowed: references to other databases or linked servers.");
        return;
    }
    if (name.SchemaIdentifier is null && _ctes.Contains(name.BaseIdentifier.Value))
        return; // a CTE, registered earlier
    var qualified = $"{name.SchemaIdentifier?.Value}.{name.BaseIdentifier.Value}";
    if (!allowedTables.Contains(qualified))
        Problems.Add($"Table '{qualified}' does not exist or is not available.");
}

The visitor also rejects variable references and user-defined function calls. allowedTables is the schema from Step 3, so it's already filtered to what agent_reader can read.

The project's full validator also checks every column against the table it's taken from, and says where the column actually lives. That came from a real failure: for "Which products are below their reorder level in the Leeds Depot?" the model wrote p.ReorderLevel instead of s.ReorderLevel, was told the column doesn't exist on catalog.Products, and declined. The fix was two-part: the validator now adds "It exists on inventory.Stock (alias s), which is already in the query", and the agent refuses to accept a CANNOT_ANSWER that contradicts the validator. See SqlValidator.cs.

The validator is the first gate. agent_reader is still the floor. How it came about, and what it changed in the benchmark, is the subject of Part 3: validating LLM-generated SQL with a real T-SQL parser. When you review generated queries by hand, a SQL formatter that understands T-SQL makes a wrong join much easier to spot. Ours runs in the browser, so the query never leaves your machine.

Step 8: Estimate the cost before running it

A query can be valid and read-only and still be far too expensive. Ask SQL Server for the estimated plan without executing anything: send SET SHOWPLAN_XML ON;, run the query text (it's compiled, not executed), sum every StmtSimple element's StatementSubTreeCost from the returned plan XML, and switch SHOWPLAN_XML OFF in a finally block before the session reverts, because under SHOWPLAN nothing executes, REVERT included.

This is why agent_reader has GRANT SHOWPLAN. It doubles as a compile check: an invalid column or a type error fails here, before execution, with SQL Server's own message. The project rejects anything above an estimated cost of 200 and tells the user to narrow the question.

Step 9: Send errors back to the model

Every rejection so far produces a precise, human-readable message. Instead of returning it to the user, return it to the model as a repair turn:

var sb = new StringBuilder("That query was not accepted:\n");
foreach (var p in problems)
    sb.Append("- ").Append(p).Append('\n');
sb.Append("\nWrite a corrected query using only tables and columns from the schema. ")
  .Append("If a column was taken from the wrong table, take it from the table that has it (joining it if needed). ")
  .Append("Reply with CANNOT_ANSWER: <reason> only if the data needed does not exist anywhere in the schema.");

messages.Add(new ChatMessage(ChatRole.Assistant, reply));
messages.Add(new ChatMessage(ChatRole.User, sb.ToString()));

The loop: parse → validate → estimate → execute; any fixable failure adds a repair turn and goes round again, up to two repairs. Security rejections are final (a write attempt isn't a typo to fix), and timeouts are final (rephrasing won't make the same query faster).

Validation, cost check and repair took the benchmark from 81% to 88%, with zero failed queries and zero unsafe SQL executed. Repairs were rare, 1.03 attempts per question on average, so latency barely moved. The question that used to invent AVG(e.Salary) now comes back as a correct refusal: the salary data isn't in the schema the agent can see.

Step 10: Expose it as an endpoint

builder.Services.AddRateLimiter(o =>
{
    o.RejectionStatusCode = StatusCodes.Status429TooManyRequests;
    o.AddPolicy("ask", http => RateLimitPartition.GetFixedWindowLimiter(
        http.Connection.RemoteIpAddress?.ToString() ?? "unknown",
        _ => new FixedWindowRateLimiterOptions { PermitLimit = 20, Window = TimeSpan.FromMinutes(1) }));
});

app.UseRateLimiter();

app.MapPost("/api/ask", async (AskRequest request, TextToSqlAgent agent, CancellationToken ct) =>
    {
        if (string.IsNullOrWhiteSpace(request.Question))
            return Results.Problem("Ask a question.", statusCode: StatusCodes.Status400BadRequest);
        try { return Results.Ok(await agent.AskAsync(request.Question, ct)); }
        catch (HttpRequestException)
        {
            return Results.Problem("The language model is not reachable. Is Ollama running?",
                statusCode: StatusCodes.Status503ServiceUnavailable);
        }
    })
    .RequireRateLimiting("ask");

public sealed record AskRequest(string Question);

Every call drives a language model and a database, so it's rate-limited per client (cap the request body size too). A local model serves one request at a time, so the project also puts a concurrency limiter in front of it. Return the SQL alongside the rows, always. A user who can read the query can catch the answers the benchmark calls silently wrong; a user who only sees a number can't. Once the endpoint is live, Part 6 adds OpenTelemetry tracing and an audit log to this pipeline, and shows what the traces revealed.

What this pipeline still gets wrong

The four questions it misses are all business definitions, not SQL: "last month" meaning the previous calendar month, not the last 30 days; average order value per order, not per order line; a category total that should include its subcategories; and a "conversion rate" the database doesn't track, which the model invented. Validation can't catch these because the SQL is valid and the rows are real. On a held-out question set the same pipeline scores 50%. A retrieved business glossary lifted that to 75%, covered in Part 4 of the AI Database Agent series.

Two more limits: schema size (every prompt carries every table the agent can see, so hundreds of tables means choosing relevant tables per question, which is a new way to be wrong) and fixed pipeline, not an agent (the model writes one query and the code drives everything else; Part 5 measures what happened when a 7B model was given tool-calling freedom).

When Text-to-SQL is the wrong tool

It earns its place when people ask many different, unplanned questions of the same data. It's the wrong tool when the same questions come up every week (use a report or dashboard with tested SQL), when nobody can check the SQL (silently wrong answers look as plausible as correct ones), when the answer depends on definitions that live in people's heads, or when the request is to change data. This pipeline is read-only by design, and writes need typed commands with their own validation and an approval step, not generated SQL.

Checklist

  • Create a WITHOUT LOGIN user with SELECT on what may be read, plus SHOWPLAN. Hide sensitive columns behind a view.
  • Run every query under EXECUTE AS USER ... WITH COOKIE, with a row cap and timeout. Clear the pool if the revert fails.
  • Send the schema as annotated DDL, read as the agent user, cached.
  • Put dialect rules, today's date and business rules in the prompt, add worked examples, and allow CANNOT_ANSWER.
  • Register the model behind IChatClient. With Ollama, raise num_ctx.
  • Parse replies defensively, validate with ScriptDom against an allow-list, and estimate cost with SET SHOWPLAN_XML ON before executing.
  • Feed errors back to the model for up to two repairs, and never repair a security rejection.
  • Measure it: build 30-odd questions with gold SQL and score by result set. Without the benchmark, none of the numbers here exist, and the silently wrong answers stay silent.

FAQ

How accurate is Text-to-SQL with a local 7B model? On our 32-question benchmark, qwen2.5-coder:7b got 53% right with a naïve prompt, 81% with a schema-aware prompt, and 88% with validation, a cost check and a repair loop. On a held-out set the same pipeline scored 50%, and 75% with a business glossary. Your numbers depend on your schema and questions.

Is it safe to run LLM-generated SQL against SQL Server? Only with layers that don't depend on the model behaving: a read-only database user, a parser-based allow-list, a cost check, a row cap and a timeout. The full set of defences is in Preventing SQL Injection in AI-Generated SQL, and the wider picture in AI Agent Security.

Can I use OpenAI, Azure OpenAI or Claude instead of Ollama? Yes. The pipeline depends only on IChatClient, so you change the registration in Step 5 and nothing else. A hosted model receives your schema and questions, and you should re-run your benchmark.

Do I need Semantic Kernel or LangChain? No. Everything here is Microsoft.Extensions.AI, Microsoft.Data.SqlClient and ScriptDom. The steps that moved the score live in the database and your own code.


The complete implementation, setup scripts, decision records and the benchmark: AfzaalLucky/ai-database-agent. For the full build story version by version, start with Part 1: naïve Text-to-SQL and why it fails silently. More articles on AI and databases are in SQL + AI.

3 views

About the author

  • AI Engineering Foundry provides practical technical content and resources for developers building production-ready AI applications with .NET, C#, large language models (LLMs), retrieval-augmented generation (RAG), AI agents, Model Context Protocol (MCP), and SQL Server. The platform focuses on real-world AI engineering, including application architecture, database integration, secure AI workflows, tool calling, vector search, deployment strategies, and production infrastructure. Through technical tutorials, implementation guides, and developer-focused resources, AI Engineering Foundry helps software developers understand how to build, integrate, and improve AI-powered systems using modern .NET technologies. Website: https://aiengfoundry.com/

No comments yet. Be the first to comment.

More from this blog