1

I tried to parse SQL queries using Microsoft.SqlServer.Management.SqlParser librairies. I didn't find any complete (or updated topics) documentation about it.

So far, here's my code:

Imports Microsoft.SqlServer.Management.SqlParser.Parser
Imports Microsoft.SqlServer.Management.SqlParser.SqlCodeDom
Imports Microsoft.SqlServer.Management.SqlParser.SqlCodeObjectModel

Dim sqlQuery As String = "SELECT Champ1 FROM MA_TABLE WHERE Champ1 = 'TITI' ORDER BY Champ2"
Dim parseOptions As ParseOptions = New ParseOptions()
Dim parseResult As ParseResult = Parser.Parse(sqlQuery, parseOptions)
If parseResult.Errors.Count = 0 Then
    Dim script = parseResult.Script
    For Each batch In script.Batches
        For Each statement In batch.Statements
            Dim selectStmt As SqlSelectStatement = TryCast(statement, SqlSelectStatement)
            
            Dim columnList As String = String.Join(", ", selectStmt.SelectSpecification.SelectElements.Select(Function(c) c.ToString()))
            
            Dim fromClause As String = String.Join(", ", selectStmt.SelectSpecification.FromClause.ToString())
If selectStmt.SelectSpecification.WhereClause IsNot Nothing Then
    Console.WriteLine("WHERE clause: " & selectStmt.SelectSpecification.WhereClause.ToString())
End If
            If selectStmt IsNot Nothing Then
                If selectStmt.SelectSpecification.OrderByClause IsNot Nothing Then
                    Console.WriteLine("ORDER BY clause: " & selectStmt.SelectSpecification.OrderByClause.ToString())
                End If
            End If
        Next
    Next
Else
    Console.WriteLine("Erreur lors du parsing de la requête :")
    For Each Error_found In parseResult.Errors
        Console.WriteLine(Error_found.Message)
    Next
End If

The only clause i can get is the order by one. How could i get select, from and where clauses ?

4
  • What happens when you try to get the other clauses? What does that code look like? Commented Oct 22, 2024 at 15:04
  • I can't use it. There are only OrderByClause and ForByClause. The other ones don't even compile. Commented Oct 22, 2024 at 16:53
  • What other ones? Show us the code you tried and tell us what happened when you tried it. Commented Oct 23, 2024 at 1:27
  • selectStmt.SelectSpecification.FromClause selectStmt.SelectSpecification.SelectElements selectStmt.SelectSpecification.WhereClause They all returned a BC30456... Commented Oct 23, 2024 at 6:36

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.