-5

I have an SQL string

select Id, Name from Order where Id ='8675' and Name ='Test'

How can I get the parts of this using C#, i.e. the from part, where part and select part to end up with:

  • select Id, Name -----> select part
  • from Order -----> from part
  • where Id ='8675' -----> where part

and any other part if required, if they have group by etc?

I have tried the following

var str = @"select Id, Name from Order where Id ='8675' and Name ='Test'";

        String[] spearator = { "from", "where" };
        String[] strlist = str.Split(spearator,
           StringSplitOptions.RemoveEmptyEntries);  

The issue i get now is that it doesnt ignore case , so if there was a From it wont work . How can i do that ?

Renee
  • 1
  • 6
  • Welcome to Stack Overflow. Please take the [tour] to learn how Stack Overflow works and read [ask] on how to improve the quality of your question. Please show your attempts you have tried and the problems/error messages you get from your attempts. – Progman Jun 06 '22 at 23:29
  • 3
    https://stackoverflow.com/questions/589096/parsing-sql-code-in-c-sharp – Daniel A. White Jun 06 '22 at 23:34
  • I have added my attempt to the question – Renee Jun 07 '22 at 01:00
  • looping through the characters, replacing to lowercase unless they're in a quote might work, but remember to handle escape characters, and subqueries are even more complex to handle – Martheen Jun 07 '22 at 04:04
  • Check out the following [parser](https://github.com/bruce-dunwiddie/tsql-parser), there is an example on the wiki page for parsing a select statement. – Karen Payne Jun 07 '22 at 10:26
  • Have you tried using [Regex.Split](https://learn.microsoft.com/en-us/dotnet/api/system.text.regularexpressions.regex.split?redirectedfrom=MSDN&view=net-6.0#overloads) ? – Schmittmuthelm Jun 07 '22 at 11:34
  • @Schmittmuthelm Regex cannot parse context-free grammar – Charlieface Jun 07 '22 at 13:26
  • Does this answer your question? [Parsing SQL code in C#](https://stackoverflow.com/questions/589096/parsing-sql-code-in-c-sharp) – Charlieface Jun 07 '22 at 13:27

1 Answers1

0
String[] strlist = str.ToLower().Split(spearator,
           StringSplitOptions.RemoveEmptyEntries);

Add ToLower() before Split().