局域网中有几个sql server服务器,我想在pb中得到所有的sql server服务器列表,该怎么做?
1、在SQL查询分析器中,输入sp_linkedservers,就可以查看已经连接上的 sql server服务器。
2、API实现该功能
返回值ls_list,各个SQLSERVER服务器是用','分隔的,自己做个拆分函数就可以分解成多个SQLSERVER服务器名称了。
代码如下:
申明API函数:
function int SQLAllocHandle(int hType,long inputHandle,ref long outputHandle) library "odbc32.dll"
function int SQLSetEnvAttr(long henv,int attribute,long valueptr,int strLength) library "odbc32.dll"
function int SQLFreeHandle(int hType,long handle) library "odbc32.dll"
function int SQLBrowseConnect(long hconn,string instring,int instringlength,ref string outstring,int outstringlength,ref int outlengthneeded) library "odbc32.dll"
定义变量:
private int SQL_HANDLE_ENV = 1
private int SQL_HANDLE_DBC = 2
private int SQL_ATTR_ODBC_VERSION = 200
private int SQL_OV_ODBC3 = 3
private int SQL_SUCCESS = 0
private int SQL_NEED_DATA = 99
private int DEFAULT_RESULT_SIZE = 1024
private string SQL_DRIVER_STR = "DRIVER=SQL SERVER"
取SQLSERVER服务器函数主体:
string ls_list
long henv = 0
long hconn = 0
string inString
inString = SQL_DRIVER_STR
string outstring
outstring = fill(' ',DEFAULT_RESULT_SIZE)
integer inStringLength
inStringLength = len(inString)
integer lenNeeded = 0
integer li_start
integer li_len
integer li_return
li_return = SQLAllocHandle(SQL_HANDLE_ENV, henv, henv)
if (SQL_SUCCESS = li_return) then
li_return = SQLSetEnvAttr(henv,SQL_ATTR_ODBC_VERSION,SQL_OV_ODBC3,0)
if (SQL_SUCCESS = li_return) then
li_return = SQLAllocHandle(SQL_HANDLE_DBC, henv, hconn)
if (SQL_SUCCESS = li_return) then
li_return = SQLBrowseConnect(hconn, inString, inStringLength, outString,DEFAULT_RESULT_SIZE,lenNeeded)
if (SQL_NEED_DATA = li_return ) then
if (DEFAULT_RESULT_SIZE < lenNeeded) then
outstring = fill(' ',lenNeeded)
li_return = SQLBrowseConnect(hconn, inString, inStringLength, outString,lenNeeded,lenNeeded)
if (SQL_NEED_DATA <> li_return) then
messagebox('Error',"Unabled to aquire SQL Servers from ODBC driver.")
return
end if
end if
ls_list = outString
li_start = pos(ls_list,"{") + 1
li_len = pos(ls_list,"}") - li_start
if ((li_start > 0) and (li_len > 0)) then
ls_list = mid(ls_list,li_start,li_len)
else
ls_list = ''
end if
end if
end if
end if
end if
if hconn <> 0 then
SQLFreeHandle(SQL_HANDLE_DBC,hconn)
end if
if henv <> 0 then
SQLFreeHandle(SQL_HANDLE_ENV,hconn);
end if
messagebox('SQLSERVER_NAME',ls_list)
return ls_list
3、以下代码经过调试正常
integer i,li_count
long ll_status
OLEObject SQLSERVER,SERVERNAME
SQLSERVER=create OLEObject
SERVERNAME=create OLEObject
SQLSERVER.connecttonewobject("SQLDMO.Application")
SERVERNAME.connecttonewobject("SQLDMO.NameList")
SERVERNAME=SQLSERVER.ListAvailableSQLServers
li_count=SERVERNAME.Count
for i=1 to li_count
ddlb_1.additem(SERVERNAME.Item(i))
next