dapidmini
dapidmini

Reputation: 1625

how to check if a database exist?

I'm trying to connect to databases in sql server 2008 using delphi 7. I have an array arr_foo that contains the names of databases. this is what my script looks like:

for i:=3 to 5 do begin
  sql := 'SELECT * FROM sys.databases WHERE name = '+quotedstr(arr_foo[i]);
  adoquery1.close;
  adoquery1.sql.text := sql;
  adoquery1.open;
  if not adoquery1.isempty then begin
    adoconnection1.close;
    adoconnection1.defaultdatabase := arr_foo[i];
    adoconnection1.open;
  end;
end;

at first, adoquery1 is already connected to adoconnection1. adoconnection1 is connected to //192.168.5.211 (which is my server).

the problem is that when I run the above script on delphi 7, it returns an error 'Property value is invalid. Please make sure the value is typed correctly' and stops at 'adoquery1.open' but when I run the query SELECT * FROM sys.databases WHERE name = 'mydb3' in SQL SERVER Management Studio 2008 it returns 1 record normally. what is wrong with my script?

Upvotes: 4

Views: 5305

Answers (1)

Devart
Devart

Reputation: 121922

Try to use DB_ID function -

IF DB_ID('AdventureWorks2008R2') IS NOT NULL
    PRINT 'exists'

Change query on this:

sql := 'SELECT ID = DB_ID(' + quotedstr(arr_foo[i]) + ')';

And check that ID value is not null.

Upvotes: 5

Related Questions