Page 1 of 1

check if table exists in a database

Posted: Tue 22 Mar 2011 09:46
by ewong
Hi,

Can someone point out how I can find if a table exists in a database
using just myQuery? Or is there a method that checks if a table
exists within a database?

Thanks

Posted: Tue 22 Mar 2011 12:44
by AndreyZ
Hello,

You can determine if a table exists in several ways:
1) by using the TMyQuery component:

Code: Select all

procedure TMainForm.BitBtnClick(Sender: TObject);
begin
  MyQuery.SQL.Text := 'SELECT * FROM information_schema.tables WHERE table_name = ''table_name''';
  MyQuery.Open;
  if not MyQuery.Eof then
    ShowMessage('exists')
  else
    ShowMessage('not exists');
end;
2) by using the GetTableNames method of the TMyConnection component:

Code: Select all

procedure TMainForm.BitBtnClick(Sender: TObject);
var
  str: TStringList;
begin
  str := TStringList.Create;
  MyConnection.GetTableNames(str);
  if str.IndexOf('table_name')  -1 then
    ShowMessage('exists')
  else
    ShowMessage('not exists');
  str.Free;
end;
3) by using the TMyMetaData component:

Code: Select all

procedure TMainForm.BitBtnClick(Sender: TObject);
begin
  MyMetaData.MetaDataKind := 'Tables';
  MyMetaData.Restrictions.Values['TABLE_NAME'] := 'table_name';
  MyMetaData.Open;
  if not MyMetaData.Eof then
    ShowMessage('exists')
  else
    ShowMessage('not exists');
end;