Converting Dynamic SQL Statements to Parameterized Queries in .NET

I’m working on a legacy .NET application that creates tons of dynamic SQL statements with inline values. These queries get passed to a central database handler class before execution. I need to build a parser that can automatically convert queries with hardcoded values into parameterized versions.

// Original query with inline values
string originalSql = "SELECT name, email, status FROM users WHERE id=123 AND category='premium'";

// Target parameterized format
string parameterizedSql = "SELECT name, email, status FROM users WHERE id=@param1 AND category=@param2";

Does anyone know of existing C# or VB.NET libraries that can handle this conversion automatically? This is meant as a temporary solution while we plan a complete data access layer rewrite.

Additional context: This is a massive application migrated from Classic ASP with thousands of inline SQL statements scattered throughout. Since all database calls go through one execution class, I want to intercept and parameterize the SQL on the fly before it hits the database.

I hit the same issue modernizing an old enterprise app. Don’t build a SQL parser from scratch - it’s a nightmare with nested queries, stored procedures, and complex expressions. I went with a hybrid approach using Microsoft.SqlServer.Management.SqlParser.Parser to tokenize statements and find literal values. Way better than reinventing the wheel. The parser walks through tokens, spots literals, and swaps them for parameters while building a parameter dictionary. Handles most common stuff like string literals with embedded quotes and numeric values. You’ll still need to manually review complex cases, but it automated about 85% of our conversion. The SqlParser package comes with SQL Server Management Objects and beats regex approaches hands down for handling SQL syntax.

sqlkata could be the way to go for this. regex can get really messy, trust me. and yeah, dapper’s def worth a look too to tidy up your db stuff.

this gets tricky fast. what about subqueries or functions? and what if values look like strings but shouldn’t be parameterized? got a backup plan when the parser screws up?