Extract parameters from an SQL query

Asked

Viewed 88 times

2

In the following query in any SQL

SELECT * FROM TABELA WHERE CAMPO1 = :PARAM1 AND CAMPO2 = :PARAM2

I need to get the names of these parameters, PARAM1 and PARAM2 and store them in a list or array.

Then I can replace it with the values.

How do I do it in C#?

  • pq you want to do replace or instead of bind?

  • I am automating some methods with Reflection, and when I pass a query in the parameter for example, I would need to know which parameters. Roughly speaking, I myself will do the manual bind of the query.

  • Wouldn’t it be the case to take all the IndexOf character : and take the name until you find a space?

1 answer

3


Can be done using regular expressions:

string query = "SELECT * FROM TABELA WHERE CAMPO1 = :PARAM1 AND CAMPO2 = AND CAMPO2 = :PARAM2";
Regex regex = new Regex(@"(:+)(\S+)", RegexOptions.Compiled | RegexOptions.Multiline);

List<string> parametros = new List<string>();
if (regex.IsMatch(query))
{
    foreach (Match match in regex.Matches(query))
    {
        parametros.Add(match.Value);
    }
}

Functional example: https://dotnetfiddle.net/rlaUwr

  • What happens if I have the following query: SELECT * FROM TABELA WHERE CAMPO1 = : AND CAMPO2 = :PARAM2?

  • Will give match only on :PARAM2

  • Wonderful, that works perfectly for what I need, thank you

Browser other questions tagged

You are not signed in. Login or sign up in order to post.