Convert a Query into a Table

Spread the love

Convert a Query into a Table

unit Unit1;

interface

uses
  Windows, Messages, SysUtils, Variants, Classes, Graphics,
  Controls, Forms,
  Dialogs, StdCtrls, Grids, DBGrids, DB, DBTables;

type
  TForm1 = class(TForm)
    Button1: TButton;
    Query1: TQuery;
    DataSource1: TDataSource;
    DBGrid1: TDBGrid;
    procedure Button1Click(Sender: TObject);
  private
    { Private declarations }
  public
    { Public declarations }
  end;

var
  Form1: TForm1;

implementation

{$R *.dfm}

procedure TForm1.Button1Click(Sender: TObject);
var
  InitQuery: TQuery;
  InitTable: TTable;
  InitBatch: TBatchMove;
begin
  InitQuery := TQuery.Create(Application);
  with InitQuery do
  begin
    DatabaseName := 'DBDEMOS';
    Close;
    SQL.Clear;
    SQL.Add('SELECT * ');
    SQL.Add('FROM customer.db');
    SQL.Add('WHERE Country="US"');
    SQL.SaveToFile('mgrInit.sql');
    try
      Open;
      try // Send the SQL result to c:\temp\INIT.DB
        InitTable := TTable.Create(Application);
        with InitTable do
        begin
          DatabaseName := 'c:\temp';
          TableName    := 'INIT';
        end;
        InitBatch := TBatchMove.Create(Application);
        with InitBatch do
        begin
          Destination := InitTable;
          Source      := InitQuery;
          Mode        := batCopy;
          Execute;
        end;
      finally
        InitTable.Free;
        InitBatch.Free;
      end;
    except
      Free;
      Abort;
    end;
    Free;
  end;
end;

end.