How to check if a database exists?

I am trying to connect to databases in SQL Server 2008 using delphi 7. I have an arr_foo array that contains the database names. this looks like my script:

 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; 

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. The value of the property is not valid. Make sure the value is entered correctly "and stops at" adoquery1.open ", but when I run the SELECT * FROM sys.databases WHERE name = 'mydb3' in SQL SERVER Management Studio 2008, it returns 1 record normally. What is wrong with my script?

+4
source share
1 answer

Try using the DB_ID function -

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

Modify the query on this:

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

And check that the ID value is not null.

+5
source

Source: https://habr.com/ru/post/1500235/


All Articles