且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

确定从ADO.NET版本的SQL Server

更新时间:2023-02-07 08:17:36

这code将确定SQL Server数据库正在使用的版本 - 2000年,2005年或2008年:

This code will determine the version of SQL Server database being used - 2000, 2005 or 2008:

try
{
    SqlConnection sqlConnection = new SqlConnection(connectionString);
    Microsoft.SqlServer.Management.Smo.Server server = new Microsoft.SqlServer.Management.Smo.Server(new Microsoft.SqlServer.Management.Common.ServerConnection(sqlConnection));

    switch (server.Information.Version.Major)
    {
      case 8:
        MessageBox.Show("SQL Server 2000");
        break;
      case 9:
        MessageBox.Show("SQL Server 2005");
        break;
      case 10:
        MessageBox.Show("SQL Server 2008");
    			break;
      default:
        MessageBox.Show(string.Format("SQL Server {0}", server.Information.Version.Major.ToString())); 
        break;   
    }
}
catch (Microsoft.SqlServer.Management.Common.ConnectionFailureException)
{
    MessageBox.Show("Unable to connect to server",
        "Invalid Server", MessageBoxButtons.OK, MessageBoxIcon.Error);

}

在code以下将做同样的,使用 NinthSense的回答:

try
{   	
    SqlConnection sqlConnection = new SqlConnection(connectionString);
    sqlConnection.Open();

    string serverVersion = sqlConnection.ServerVersion;
    string[] serverVersionDetails = serverVersion.Split( new string[] {"."}, StringSplitOptions.None);

    int versionNumber = int.Parse(serverVersionDetails[0]);

    switch (versionNumber)
    {
    	case 8:
        	MessageBox.Show("SQL Server 2000");
    		break;
    	case 9:
    		MessageBox.Show("SQL Server 2005");
    		break;
    	case 10:
    		MessageBox.Show("SQL Server 2008");
    		break;
    	default:
    		MessageBox.Show(string.Format("SQL Server {0}", versionNumber.ToString()));  
    		break;  
    }
}
catch (Exception ex)
{
    MessageBox.Show(string.Format("Unable to connect to server due to exception: {1}", ex.Message),
        "Invalid Connection!", MessageBoxButtons.OK, MessageBoxIcon.Error);

}
finally
{
    sqlConnection.Close();
}