Question : How to detect if SQL Server 2005 or 2008 is installed

Hi,

How can I detect if SQL Server 2005 or 2008 is installed on a computer from within a Delphi application?
Preferably not by using the registry.

I found some code in C# that might do this??? (see below).
1:
2:
3:
4:
5:
6:
7:
8:
9:
10:
11:
12:
13:
14:
15:
16:
17:
18:
19:
20:
21:
22:
23:
24:
25:
26:
27:
28:
29:
30:
31:
32:
33:
34:
35:
36:
37:
38:
39:
40:
41:
42:
43:
44:
45:
46:
47:
48:
49:
50:
51:
52:
53:
54:
55:
56:
57:
58:
59:
60:
61:
62:
63:
64:
65:
66:
67:
68:
69:
70:
71:
72:
73:
74:
75:
76:
77:
78:
79:
80:
81:
82:
83:
84:
85:
86:
87:
88:
89:
90:
91:
92:
93:
94:
95:
96:
97:
98:
99:
100:
101:
102:
103:
104:
105:
106:
107:
108:
109:
110:
111:
112:
113:
114:
115:
116:
117:
118:
119:
120:
121:
122:
123:
124:
125:
126:
127:
128:
129:
130:
131:
132:
133:
134:
135:
136:
137:
138:
139:
140:
141:
142:
143:
144:
145:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Management;
namespace ExpressDetection
{
    class Program
    {
        static void Main(string[] args)
        {
            if (!EnumerateSQLInstances())
            {
                Console.WriteLine("There are no instances of SQL Server 2005 or SQL Server 2008 installed");
            }
        }
        /// <summary>
        /// Enumerates all SQL Server instances on the machine.
        /// </summary>
        /// <returns></returns>
        public static bool EnumerateSQLInstances()
        {
            string correctNamespace = GetCorrectWmiNameSpace();
            if (string.Equals(correctNamespace, string.Empty))
            {
                return false;
            }
            string query = string.Format("select * from SqlServiceAdvancedProperty where SQLServiceType = 1 and PropertyName = 'instanceID'");
            ManagementObjectSearcher getSqlEngine = new ManagementObjectSearcher(correctNamespace, query);
            if (getSqlEngine.Get().Count == 0)
            {
                return false;
            }
            Console.WriteLine("SQL Server database instances discovered :");
            string instanceName = string.Empty;
            string serviceName = string.Empty;
            string version = string.Empty;
            string edition = string.Empty;
            Console.WriteLine("Instance Name \t ServiceName \t Edition \t Version \t");
            foreach (ManagementObject sqlEngine in getSqlEngine.Get())
            {
                serviceName = sqlEngine["ServiceName"].ToString();
                instanceName = GetInstanceNameFromServiceName(serviceName);
                version = GetWmiPropertyValueForEngineService(serviceName, correctNamespace, "Version");
                edition = GetWmiPropertyValueForEngineService(serviceName, correctNamespace, "SKUNAME");
                Console.Write("{0} \t", instanceName);
                Console.Write("{0} \t", serviceName);
                Console.Write("{0} \t", edition);
                Console.WriteLine("{0} \t", version);
            }
            return true;
        }
        /// <summary>
        /// Method returns the correct SQL namespace to use to detect SQL Server instances.
        /// </summary>
        /// <returns>namespace to use to detect SQL Server instances</returns>
        public static string GetCorrectWmiNameSpace()
        {
            String wmiNamespaceToUse = "root\\Microsoft\\sqlserver";
            List<string> namespaces = new List<string>();
            try
            {
                // Enumerate all WMI instances of
                // __namespace WMI class.
                ManagementClass nsClass =
                    new ManagementClass(
                    new ManagementScope(wmiNamespaceToUse),
                    new ManagementPath("__namespace"),
                    null);
                foreach (ManagementObject ns in
                    nsClass.GetInstances())
                {
                    namespaces.Add(ns["Name"].ToString());
                }
            }
            catch (ManagementException e)
            {
                Console.WriteLine("Exception = " + e.Message);
            }
            if (namespaces.Count > 0)
            {
                if (namespaces.Contains("ComputerManagement10"))
                {
                    //use katmai+ namespace
                    wmiNamespaceToUse = wmiNamespaceToUse + "\\ComputerManagement10";
                }
                else if (namespaces.Contains("ComputerManagement"))
                {
                    //use yukon namespace
                    wmiNamespaceToUse = wmiNamespaceToUse + "\\ComputerManagement";
                }
                else
                {
                    wmiNamespaceToUse = string.Empty;
                }
            }
            else
            {
                wmiNamespaceToUse = string.Empty;
            }
            return wmiNamespaceToUse;
        }
        /// <summary>
        /// method extracts the instance name from the service name
        /// </summary>
        /// <param name="serviceName"></param>
        /// <returns></returns>
        public static string GetInstanceNameFromServiceName(string serviceName)
        {
            if (!string.IsNullOrEmpty(serviceName))
            {
                if (string.Equals(serviceName, "MSSQLSERVER", StringComparison.OrdinalIgnoreCase))
                {
                    return serviceName;
                }
                else
                {
                    return serviceName.Substring(serviceName.IndexOf('$') + 1, serviceName.Length - serviceName.IndexOf('$')-1);
                }
            }
            else
            {
                return string.Empty;
            }
        }
        /// <summary>
        /// Returns the WMI property value for a given property name for a particular SQL Server service Name
        /// </summary>
        /// <param name="serviceName">The service name for the SQL Server engine serivce to query for</param>
        /// <param name="wmiNamespace">The wmi namespace to connect to </param>
        /// <param name="propertyName">The property name whose value is required</param>
        /// <returns></returns>
        public static string GetWmiPropertyValueForEngineService(string serviceName, string wmiNamespace, string propertyName)
        {
            string propertyValue = string.Empty;
            string query = String.Format("select * from SqlServiceAdvancedProperty where SQLServiceType = 1 and PropertyName = '{0}' and ServiceName = '{1}'", propertyName, serviceName);
            ManagementObjectSearcher propertySearcher = new ManagementObjectSearcher(wmiNamespace, query);
            foreach (ManagementObject sqlEdition in propertySearcher.Get())
            {
                propertyValue = sqlEdition["PropertyStrValue"].ToString();
            }
            return propertyValue;
        }
    }
}

Answer : How to detect if SQL Server 2005 or 2008 is installed

My source just looked for a specific instance of SQL Server Express, I've found a little time and modified the code to enumerate the instances based a little on the C# code you posted at the top.
1:
2:
3:
4:
5:
6:
7:
8:
9:
10:
11:
12:
13:
14:
15:
16:
17:
18:
19:
20:
21:
22:
23:
24:
25:
26:
27:
28:
29:
30:
31:
32:
33:
34:
35:
36:
37:
38:
39:
40:
41:
42:
43:
44:
45:
46:
47:
48:
49:
50:
51:
52:
53:
54:
55:
56:
57:
58:
59:
60:
61:
62:
63:
64:
65:
66:
67:
68:
69:
70:
71:
72:
73:
74:
75:
76:
77:
78:
79:
80:
81:
82:
83:
84:
85:
86:
87:
88:
89:
90:
91:
92:
93:
94:
95:
96:
97:
98:
99:
100:
101:
102:
103:
104:
105:
106:
107:
108:
109:
110:
111:
112:
113:
114:
115:
116:
117:
118:
function GetSQLInstances(Instances: TStrings): Boolean;
  function GetInstanceNameFromServiceName(const ServiceName: string): string;
  const
    SQLSERVER = 'MSSQLSERVER';
  begin
    if ServiceName = '' then
      Result := ''
    else
    begin
      if UpperCase(ServiceName) = SQLSERVER then
        Result := ServiceName
      else
        Result := Copy(ServiceName, Pos('$', ServiceName)+1, Length(ServiceName)-Pos('$', ServiceName));
    end;
  end;
  function GetWMIPropertyValueForEngineService(const PropertyName, ServiceName, WMINameSpace: string): string;
  var
    SWL: TSWbemLocator;
    SWServ: ISWbemServices;
    SWObjSet: ISWbemObjectSet;
    Enum: IEnumVariant;
    tempObj: OleVariant;
    Value: Cardinal;    
    SWObj: ISWbemObject;
    SWPropSet: ISWbemPropertySet;
    sQry: string;
  begin
    SWL := TSWbemLocator.Create(nil);
    try
      try
        SWServ := SWL.ConnectServer('', WMINameSpace, '', '', '', '', 0, nil);
        sQry := Format('select * from SqlServiceAdvancedProperty where SQLServiceType = 1 and PropertyName = ''%s'' and ServiceName = ''%s''', [PropertyName, ServiceName]);
        SWObjSet := SWServ.ExecQuery(sQry, 'WQL', wbemFlagReturnImmediately, nil);
        if SWObjSet.Count = 0 then
        begin
          Result := '';
          Exit;
        end;
        //
        Enum := (SWObjSet._NewEnum) as IEnumVariant;
        while (Enum.Next(1, tempObj, Value) = S_OK) do
        begin
          SWObj := IUnknown(tempObj) as SWBemObject;
          SWPropSet := SWObj.Properties_;
          Result := SWPropSet.Item('PropertyStrValue', 0).Get_Value;
        end;
      except
        on E: Exception do
        begin
          //WriteLn('Error: ' + e.Message);
          Result := '';
        end;
      end;
    finally
      SWL.Disconnect;
      FreeAndNil(SWL);
    end;
  end;
const
  WMI_NAMESPACES_TO_CHECK: array[0..1] of string = ('ComputerManagement', 'ComputerManagement10');
var
  GetSqlExpress: TSWbemLocator;
  Services: ISWbemServices;
  ObjectSet: ISWbemObjectSet;
  SObject: ISWbemObject;
  propSet: ISWbemPropertySet;
  Enum: IEnumVariant;
  tempObj: OleVariant;
  Value: Cardinal;
  //
  sQry: string;
  serviceName: string;
  WMIPath: string;
  i: Integer;
begin
  Result := False;
  Instances.Clear;
  for i := 0 to 1 do
  begin
    WMIPath := Format('root\Microsoft\SqlServer\%s', [WMI_NAMESPACES_TO_CHECK[i]]);
    GetSqlExpress := TSWbemLocator.Create(nil);
    try
      try
        Services := GetSqlExpress.ConnectServer('', WMIPath, '', '', '', '', 0, nil);
        sQry := Format('SELECT * FROM SqlServiceAdvancedProperty WHERE SQLServiceType = 1 AND PropertyName = ''instanceID''', [{SQL_INSTANCE}]);
        ObjectSet := Services.ExecQuery(sQry, 'WQL', wbemFlagReturnImmediately, nil);
        if ObjectSet.Count = 0 then
        begin
          Continue;
        end;
        //
        Enum := (ObjectSet._NewEnum) as IEnumVariant;
        while (Enum.Next(1, tempObj, Value) = S_OK) do
        begin
          SObject := IUnknown(tempObj) as SWBemObject;
          propSet := SObject.Properties_;
          serviceName := propSet.Item('ServiceName', 0).Get_Value;
          // Service, Instance, Version, Edition
          Instances.Add(Format('%s, %s, %s, %s',
            [serviceName,
              GetInstanceNameFromServiceName(serviceName),
              GetWMIPropertyValueForEngineService('Version', serviceName, WMIPath),
              GetWMIPropertyValueForEngineService('SKUNAME', serviceName, WMIPath)]));
        end;
        Result := True;
      except
        on E: Exception do
        begin
          //WriteLn('Error: ' + e.Message);
          Result := False;
        end;
      end;
    finally
      GetSqlExpress.Disconnect;
      FreeAndNil(GetSqlExpress);
    end;
  end;
end;
Random Solutions  
 
programming4us programming4us