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 ?
selectStmt.SelectSpecification.FromClauseselectStmt.SelectSpecification.SelectElementsselectStmt.SelectSpecification.WhereClauseThey all returned a BC30456...