Mirror

Enumerate MS-SQL Servers via SQL-DMO into TStrings (Views: 14845)

Problem/Question/Abstract:

Function to load a StringList with MS-SQL Servers on a Network via SQL-DMO. MS-SQL DMO is a COM/OLE object that can do many things, in this article we just enumerate the SQL Servers on a Network. "List SQL servers on the network" by Tommy Andersen deals with this issue by using WinSock and a comment supplies a solution using CoApplication.Create. This article solves the issue by using CreateOleObject('SQLDMO.SQLServer'). The function returns true if successful.

// Declaration

function EnumSqlServers(AStrings: TStrings): boolean;

// Eg.
EnumSqlServers(Memo1.Lines);

Answer:

uses ComObj, Variants; {Variants is for Delphi 7}

// ====================================================
// Load SQL Servers on a Network into a string list
// ====================================================

function EnumSqlServers(AStrings: TStrings): boolean;
var
oDmo, oApp, oServers: OleVariant;
bResult: boolean;
i: integer;
begin
AStrings.Clear;

try
oDMO := CreateOleObject('SQLDMO.SQLServer');
oApp := oDMO.Application;
oServers := oApp.ListAvailableSQLServers;

try
AStrings.BeginUpdate;
for i := 1 to oServers.Count do
AStrings.Add(oServers.Item(i));
finally
AStrings.EndUpdate;
end;

bResult := true;
except
bResult := false;
end;

oServers := Unassigned;
oApp := Unassigned;
oDMO := Unassigned;

Result := bResult;
end;


<< Back to main page