sql查詢語句的拼接小技巧(高手勿噴)

1. 基本的查詢語句後面加上 WHERE 1=1,便於增長查詢條件。數據庫

ASkStr := 'select * from Twork where 1=1 ';
if length(cxTEworkid.Text) <> 0 then 
begin
ASkStr := ASkStr + ' and GWORKID like ' +
quotedstr('%' + cxTEworkid.Text + '%')
end;

  

2. 多表查詢能夠用一個字符串代替一個表。邏輯上更清晰。函數

  

WorkTable = 'select GWorkId from TWork where 1=1 ';
PayTable = 'select sum(GXMtotal) as SGXMtotal,GXMType from TPAY where GWorkId In ';
PayGroupBy = ' Group By GXMType ';
ASkStr := PayTable + ' ( ' + WorkTable + tmpwhere + ' ) ' + PayGroupBy;

 

3.本身定義一個鏈接函數,判斷數據庫初始化是否成功,便於控制。blog

  

function Tdm.InitDbOk: boolean;
begin
  result := true;
  if fileexists(DBFileName) then
  begin
    FDConn.DriverName := 'SQLite';
    FDConn.LoginPrompt := false;
    FDConn.Params.Clear;
    FDConn.Params.Values['Database'] := DBFileName;
    FDConn.Params.Values['DriverID'] := 'SQLite';
    FDConn.Params.Values['CharacterSet'] := 'utf8';
    try
      FDConn.Connected := true;
    except
      result := false;
    end;
  end
  else
    result := false;
end;
相關文章
相關標籤/搜索