Page 1 of 1

Enumerate SQL servers

Posted: Tue 18 Mar 2014 11:13
by dpallas
Is there a function / procedure for enumerating MS SQL servers?

Re: Enumerate SQL servers

Posted: Wed 19 Mar 2014 23:39
by dpallas
I found a solution, but it doesn't enumerate ms sql instances

Code: Select all

Uses
  MSServicesUni;

.... 

Var
  Lista   : TStrings;
  ServEnum: TMSServerEnumerator;
begin
  Lista:=TStringList.Create;
  ServEnum:=TMSServerEnumerator.Create;
  ServEnum.GetServerList(Lista);
  ServEnum.Free;
  EdServers.Lines.AddStrings(Lista);
  Lista.Free;
end;

Re: Enumerate SQL servers

Posted: Thu 20 Mar 2014 12:37
by AlexP
To obtain names of existing instances on the server, you can use the UniConnection.GetDatabaseNames method. To obtain the list of instances with this method, connection to the server must be established.

Code: Select all

program Project1;

{$APPTYPE CONSOLE}

uses
  MSServicesUni,
  SysUtils,
  Classes,
  Uni,
  SQLServerUniProvider,
  ActiveX;

Var
  ServerList, InstanceList: TStringList;
  ServEnum: TMSServerEnumerator;
  i, j: integer;
  UniConnection: TUniConnection;
begin
  CoInitialize(nil);
  try
    ServerList := TStringList.Create;
    try
      ServEnum := TMSServerEnumerator.Create;
      try
        ServEnum.GetServerList(ServerList);
        UniConnection := TUniConnection.Create(nil);
        try
          UniConnection.ProviderName := 'SQL Server';
          UniConnection.Username := 'sa';
          for i := 0 to ServerList.Count - 1 do begin
            Writeln(ServerList[i]);
            UniConnection.Server := ServerList[i];
            UniConnection.Connect;
            InstanceList := TStringList.Create;
            try
              UniConnection.GetDatabaseNames(InstanceList);
              for  j := 0 to InstanceList.Count - 1 do
                Writeln(#9 + InstanceList[j]);
            finally
              InstanceList.Free;
              UniConnection.Disconnect;
            end;
          end;
        finally
          UniConnection.Free;
        end;
      finally
        ServEnum.Free;
      end;
    finally
      ServerList.Free;
    end;
  finally
    CoUninitialize;
    readln;
  end;
end.