Microsoft.SqlServer.Management.SqlParser provides T-SQL parsing functionality.
$ dotnet add package Microsoft.SqlServer.Management.SqlParser.NativeThis nuget package provides both MSIL and native Ahead-of-Time compiled (AoT) versions of Microsoft.SqlServer.Management.SqlParser for use by Net8.0 applications.
The AoT binaries can be consumed by AoT console applications.
There's one entrypoint exposed specifically for use by native callers such as C++ applications - Parse
This is the prototype
[System.Text.Json.Serialization.JsonSourceGenerationOptions(PropertyNamingPolicy = System.Text.Json.Serialization.JsonKnownNamingPolicy.CamelCase)]
[System.Text.Json.Serialization.JsonSerializable(typeof(ParseResultBase))]
internal partial class ParseResultContext : System.Text.Json.Serialization.JsonSerializerContext
{
}
public static class NativeApi
{
/// <summary>
/// Native API for parsing TSQL
/// </summary>
/// <param name="pString">The text to parse, encoded in UTF 8</param>
/// <param name="pVersion">An identifier of the version, encoded in UTF8. Can be a number associated with a
/// SQL Server version like "160" or a member of the TransactSqlVersion enumeration</param>
/// <returns></returns>
[UnmanagedCallersOnly(EntryPoint = "Parse")]
public static IntPtr Parse(IntPtr pString, IntPtr pVersion)
{
}
}
This is a sample C++ program listing to call Parse and print the result.
#include <windows.h>
typedef char* (*parse)(const char*, const char*);
int main()
{
HMODULE h = ::LoadLibrary(L"win-x64\\native\\Microsoft.SqlServer.Management.SqlParser.dll");
parse parser = (parse)::GetProcAddress(h, "Parse");
char* result = parser("sel b from foo", "160");
printf(result);
}
Output:
{"batchCount":1,"parseErrors":[{"message":"Incorrect syntax near \u0027from\u0027.","start":{"lineNumber":1,"columnNumber":7,"offset":6},"end":{"lineNumber":1,"columnNumber":11,"offset":10},"isWarning":false,"type":1}],"resultId":1}