一、 SQL DMO
描述:SQL Distributed Management Objects(SQL分布式管理对象),存在于SQLDMO.dll文件中,实际上是一个COM 对象,通过调用SQL DMO的ListAvailableSQLServers方法取得。
列表类型:列举装有“客户端”和“服务端”的计算机。
适用条件:装有 SQL Server,且有SQLDMO.dll文件。
速度:中
调用示例:GetSQLServerList(ListBox1.items);
代码:
uses
ComObj;
function GetSQLServerList(var AList: TStrings): Boolean;
var
SQLServerApp: Variant;
ServerList: Variant;
i: Integer;
begin
Result := True;
try
SQLServerApp := CreateOleObject(''SQLDMO.Application'');
ServerList := SQLServerApp.ListAvailableSQLServers;
for i := 1 to ServerList.Count do
AList.Add(ServerList.Item(i));
SQLServerApp := Unassigned;
ServerList := Unassigned;
except
Result := False;
end;
end;
二、 NetServerEnum
描述:网络服务函数,存在于NetApi32.dll文件中;通过NetServerEnum函数可取得装有SQL Server服务端的计算机列表,只装有SQL Server客户端的计算机将不会被列举其中;如果一台计算机的SQL Server服务刚刚启动,那么此函数将会过很久才能取到该计算机。
列表类型:仅列举装有“服务端”的计算机。
适用条件:有NetApi32.dll文件。
速度:快
调用示例:GetSQLServerList(ListBox1.items);
代码:
type
NET_API_STATUS = DWORD;
PServerInfo100 = ^TServerInfo100;
_SERVER_INFO_100 = record
sv100_platform_id: DWORD;
sv100_name: LPWSTR;
end;
{$EXTERNALSYM _SERVER_INFO_100}
TServerInfo100 = _SERVER_INFO_100;
SERVER_INFO_100 = _SERVER_INFO_100;
{$EXTERNALSYM SERVER_INFO_100}
const
NERR_Success = 0;
MAX_PREFERRED_LENGTH = DWORD(-1);
SV_TYPE_SQLSERVER = $00000004;
function NetApiBufferAllocate(ByteCount: DWORD; var Buffer: Pointer):
NET_API_STATUS; stdcall; external ''netapi32.dll'' name ''NetApiBufferAllocate'';
function NetServerEnum(ServerName: LPCWSTR; Level: DWORD; var BufPtr: Pointer;
PrefMaxLen: DWORD; var EntriesRead: DWORD; var TotalEntries: DWORD;
ServerType: DWORD; Domain: LPCWSTR; ResumeHandle: PDWORD): NET_API_STATUS;
stdcall; external ''netapi32.dll'' name ''NetServerEnum'';
function NetApiBufferFree(Buffer: Pointer): NET_API_STATUS; stdcall; external
''netapi32.dll'' name ''NetApiBufferFree'';
function GetSQLServerList(var AList: TStrings; pwcServerName: PWChar = nil;
pwcDomain: PWChar = nil): Boolean;
var
NetAPIStatus: DWORD;
dwLevel: DWORD;
pReturnSvrInfo: Pointer;
dwPrefMaxLen: DWORD;
dwEntriesRead: DWORD;
dwTotalEntries: DWORD;
dwServerType: DWORD;
dwResumeHandle: PDWORD;
pCurSvrInfo: PServerInfo100;
i, j: Integer;
begin
Result := True;
try
dwLevel := 100;
pReturnSvrInfo := nil;
dwPrefMaxLen := MAX_PREFERRED_LENGTH;
dwEntriesRead := 0;
dwTotalEntries := 0;
dwServerType := SV_TYPE_SQLSERVER; //服务器类型
dwResumeHandle := nil;
NetApiBufferAllocate(SizeOf(pReturnSvrInfo), pReturnSvrInfo);
try
NetAPIStatus := NetServerEnum(pwcServerName, dwLevel, pReturnSvrInfo,
dwPrefMaxLen, dwEntriesRead, dwTotalEntries, dwServerType, pwcDomain,
dwResumeHandle);
if ((NetAPIStatus = NERR_Success) or (NetAPIStatus = ERROR_MORE_DATA)) and
(pReturnSvrInfo <> nil) then
begin
pCurSvrInfo := pReturnSvrInfo;
// 循环取得所有SQL Server服务器
i := 0;
j := dwEntriesRead;
while i < j do
begin
if pCurSvrInfo = nil then
Break;
with AList