sql-server – SQL语法解析器在Delphi for SQL Server

前端之家收集整理的这篇文章主要介绍了sql-server – SQL语法解析器在Delphi for SQL Server前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我在Delphi(2010)为sql Server寻找一个好的sql解析器.我需要这样的东西来解析一个查询提取:select list,where and order by子句.无论是商业还是开源解决方案都没关系.它也可以是一个DLL(当然用任何语言编写),但是我更喜欢使用VCL组件.

解决方法

Rafael Delphi自带了一个位于DBCommon单元中的sql解析器

检查这些功能

function NextsqlToken(var p: PAnsiChar; out Token: AnsiString; CurSection: TsqlToken): TsqlToken; overload;
function NextsqlToken(var p: PWideChar; out Token: WideString; CurSection: TsqlToken): TsqlToken; overload;
function NextsqlToken(var p: PChar; out Token: String; CurSection: TsqlToken): TsqlToken; overload;

function GetIndexForOrderBy(const sql: WideString; DataSet: TDataSet): TIndexDef;
function GetTableNameFromsql(const sql: WideString): WideString;
function GetTableNameFromQuery(const sql: Widestring): Widestring;
function AddParamsqlForDetail(Params: TParams; sql: WideString; Native: Boolean; QuoteChar: WideString = ''): WideString;
function IsMultiTableQuery(const sql: WideString): Boolean;
function sqlRequiresParams(const sql: WideString): Boolean;

function NextsqlTokenEx(var p: PWideChar; out Token: UnicodeString; CurSection: TsqlToken; IdOption: IDENTIFIEROption): TsqlToken; overload;
function NextsqlTokenEx(var p: PWideChar; out Token: WideString; CurSection: TsqlToken; IdOption: IDENTIFIEROption): TsqlToken; overload;
function NextsqlTokenEx(var p: PAnsiChar; out Token: AnsiString; CurSection: TsqlToken; IdOption: IDENTIFIEROption): TsqlToken; overload;
function GetTableNameFromsqlEx(const sql: WideString; IdOption: IDENTIFIEROption): WideString;

这是一个非常简单的示例来显示如何解析sql语句并获取所有元素.

uses
  TypInfo,DbCommon,SysUtils;


const
  Strsql ='Select Field1,Field2,54 field3,Field4 from Mytable1 Order by Field1,Field5';

procedure Parsesql(Const sql : string);
var
  sqlToken     : TsqlToken;
  CurSection   : TsqlToken;
  Start        : PWideChar;
  Token        : WideString;
  IdOption     : IDENTIFIEROption;
begin
  IdOption   :=idMixCase;
  Start      :=PWideChar(Strsql);
  CurSection := stUnknown;
  repeat
    sqlToken := NextsqlTokenEx(Start,Token,CurSection,IdOption);
    if sqlToken<>stEnd then
    Writeln(Format('Type %s Token %s',[GetEnumName(TypeInfo(TsqlToken),integer(sqlToken)),Token]));
    CurSection := sqlToken;
  until sqlToken in [stEnd];
end;



begin
  try
    Parsesql(Strsql);
  except
    on E: Exception do
      Writeln(E.ClassName,': ',E.Message);
  end;
  Readln;
end.

这将返回

Type stSelect Token Select
Type stFieldName Token Field1
Type stFieldName Token Field2
Type stNumber Token 54
Type stFieldName Token field3
Type stFieldName Token Field4
Type stFrom Token from
Type stTableName Token Mytable1
Type stOrderBy Token Order by
Type stFieldName Token Field1
Type stFieldName Token Field5
原文链接:https://www.f2er.com/mssql/75587.html

猜你在找的MsSQL相关文章