Showing posts with label Sql Server Version. Show all posts
Showing posts with label Sql Server Version. Show all posts

November 14, 2019

Sql Server Version Finder using Value Tuples in C# Version 8

Here is an example of using the new tuples in Version 8 of the C# compiler. I've tried to use these tuples in a way which makes them as readable as possible.

public class SqlVersionFinder
{
  public (string version, string date, string copyright, string edition)
                          GetSqlVersion(string server = @".\")
  {
    // Use named arguments so that the tuple is easy to read and maintain
    var res = (version: "", date: "", copyright: "", edition: "");

    using (var connection = new SqlConnection(String.Format(
        "Server={0};Database=master;Trusted_Connection=True;",
         server)))
    {
      connection.Open();
      var sqlResult = "";

      using (var command = connection.CreateCommand())
      {
        command.CommandText = " SELECT @@VERSION";
        sqlResult = command.ExecuteScalar() as string ?? "";
      }
      if (!string.IsNullOrEmpty(sqlResult))
      {
        var versionInfo = sqlResult.Split(new[] { "\n\t" }, 
                            System.StringSplitOptions.None);
        if (versionInfo != null && versionInfo.Length >= 4)
        {
           res.version = versionInfo[0] ?? "";
           res.date = versionInfo[1] ?? "";
           res.copyright = versionInfo[2] ?? "";
           res.edition = versionInfo[3] ?? "";
        }
      }
    }
    return res;
  }
}
Here is the test code (from a Console app) that retrieves Sql Server Version information
SqlVersionFinder sqlVersionFinder = new SqlVersionFinder();
var res = sqlVersionFinder.GetSqlVersion();
Console.WriteLine("Version:   " + res.version);
Console.WriteLine("Date:      " + res.date);
Console.WriteLine("Copyright: " + res.copyright);
Console.WriteLine("Edition:   " + res.edition);
Output looks like this:

Version: Microsoft SQL Server 2016 (RTM) - 13.0.1601.5 (X64)
Date: Apr 29 2016 23:23:58
Copyright: Copyright (c) Microsoft Corporation
Edition: Standard Edition (64-bit) on Windows 10 Enterprise 6.3 (Build 17134: )