Delphi7从SQL Server数据库中读取SQL语句并替换变量

  • 亚历山高
  • 2024-06-21
  • 474 人已阅读

举例说明,原始SQL语句:

SELECT cBuyCode,cPartName,cPartStd,cUnit FROM S_PurchasingDetail 

where convert(nvarchar(10),dtTextDate,23) between '@@dDate1' and '@@dDate2' 


其中@@dDate1 和@@dDate2 是变量,使用的时候需要替换实际值。

存储到数据表中:

image.png

在Delphi中使用该SQL:


var

  PRSQL,Fdate1,Fdate2:String;


  Fdate1:=FormatDateTime('yyyy-MM-dd',DateTimePicker3.Date);

  Fdate2:=FormatDateTime('yyyy-MM-dd',DateTimePicker4.Date);


  ado.Close;

  ado.SQL.Clear;

  ado.SQL.Add('select mRtSql from B_ReportTable where cRtCode=''0202'' ');

  ado.Open;


  if ado.RecordCount=1 then

  begin

    PRSQL:=ado.FieldByName('mRtSql').AsString;


    PRSQL:=StringReplace(PRSql,'@@dDate1',Fdate1,[rfReplaceAll, rfIgnoreCase]);

    PRSQL:=StringReplace(PRSql,'@@dDate2',Fdate2,[rfReplaceAll, rfIgnoreCase]);


    ADOQuery1.Close;

    ADOQuery1.SQL.Clear;

    ADOQuery1.SQL.Add(PRSQL);

    ADOQuery1.Open;

  end;



Top