获取SQL服务器组中可用服务器的列表

时间:2020-03-06 14:51:44  来源:igfitidea点击:

如何提取SQL Server组中可用SQL Server的列表?我打算将该列表放在VB.NET的组合框中。

解决方案

我唯一知道的方法是使用命令行:

osql -L

但是我发现以下文章似乎可以解决我们在填充组合框时的特定目标:

http://www.sqldbatips.com/showarticle.asp?ID=45

在CI中使用了对odbc32.dll的调用

例如:

[DllImport("odbc32.dll", CharSet = CharSet.Ansi)]

private static extern short SQLBrowseConnect(
IntPtr hconn, StringBuilder inString,
short inStringLength, StringBuilder outString, short outStringLength, out short 
outLengthNeeded);

该功能的文档在MSDN上

如果我们不想被Ben的文章所使用的SQL SMO所束缚,则可以执行以下操作来发现网络上的所有SQL Server:

Private Sub cmbServer_DropDown(ByVal sender As Object, ByVal e As System.EventArgs) Handles cmbServer.DropDown
    Dim oTable As Data.DataTable
    Dim lstServers As List(Of String)
    Try
        If cmbServer.Items.Count = 0 Then
            System.Windows.Forms.Cursor.Current = System.Windows.Forms.Cursors.WaitCursor
            oTable = System.Data.Sql.SqlDataSourceEnumerator.Instance.GetDataSources

            For Each oRow As DataRow In oTable.Rows
                If oRow("InstanceName").ToString = "" Then
                    cmbServer.Items.Add(oRow("ServerName"))
                Else
                    cmbServer.Items.Add(oRow("ServerName").ToString & "\" & oRow("InstanceName").ToString)
                End If
            Next oRow
        End If
    Catch ex As Exception
        ErrHandler("frmLogin", "cmbServer_DropDown", ex.Source, ex.Message, Ex.InnerException)
    Finally
        System.Windows.Forms.Cursor.Current = System.Windows.Forms.Cursors.Default

        If oTable IsNot Nothing Then
            oTable.Dispose()
        End If
    End Try
End Sub

SqlDataSourceEnumerator类很不错,因为它使我们可以直接从2.0框架进行SQL Server发现。