'Find path to a program (sqlcmd) installed by child subinstaller of Inno Setup

In my scenario I need to run .sql script at the end of my setup with sqlcmd.exe. But each version of SQL Server uses different paths for sqlcmd.

I'm trying some solutions to use sqlcmd but none work. As a last test I created an installer just to run my script but even this doesn't recognize sqlcmd as a command. Is there a way to retrieve the sqlcmd path with a function in order to pass the value to [Run] section? Any suggestions are welcome. Thanks

This is my code I'm trying

Main installer.exe

[Setup]
PrivilegesRequired=admin

[Files]
; sql server 2019 Express 
Source: "..\PREREQUIREMENTS\SQL\SQLSERVER\2019\SQLEXPR_x64_ENU.exe"; \
    DestDir: "{tmp}"; DestName: "SQLSERVER2019.exe"; Flags: ignoreversion; \
    MinVersion: 10.0.17134; Tasks: SQL
; sql server 2014 Express 
Source: "..\PREREQUIREMENTS\SQL\SQLSERVER\2014\SQLEXPR_x64_ENU.exe"; \
    DestDir: "{tmp}"; DestName: "SQLSERVER2014SP3.exe"; Flags: ignoreversion; \
    OnlyBelowVersion: 10.0.17134; Tasks: SQL
; sql management studio 18 
Source: "..\PREREQUIREMENTS\SQL\SSMS\SSMS-Setup-ENU.exe"; DestDir: "{tmp}"; \
    DestName: "SSMS18.exe"; Flags: ignoreversion; Tasks: SSMS
; SQLCMD
Source: "src\DB\ADM_DB_installer.exe"; DestDir: "{tmp}"; Flags: ignoreversion; \
    Components: ADM

ADM_DB_installer.exe

[Setup]
PrivilegesRequired=admin

[Run]
Filename: "sqlcmd.exe"; \
    Parameters: "-v ADMPRIMARY=""{code:GetSQLVar|DBPATH}"" ADMDATA=""{code:GetSQLVar|DBPATH}"" ADMINDEX=""{code:GetSQLVar|DBPATH}"" ADMLOG=""{code:GetSQLVar|DBPATH}"" -S {code:GetSQLVar|SQLSERVER}\{code:GetSQLVar|INSTANCE} -U sa -P {code:GetSQLVar|SAPWD} -i ""{tmp}\CREATE_ADM_DB_1.0.0.sql"" -o ""{code:GetSQLVar|DBPATH}\log.txt"""


Solution 1:[1]

There might be a better solution, but what you can do is to read the PATH from registry and use FileSearch to find the program.

[Run]
Filename: "{code:FileSearchInPath|sqlcmd.exe}"; Parameters: "..."
[Code]
const
  EnvironmentKey = 'SYSTEM\CurrentControlSet\Control\Session Manager\Environment';

function FileSearchInPath(FileName: string): string;
var
  Path: string;
begin
  Result := '';
  if not RegQueryStringValue(HKLM, EnvironmentKey, 'PATH', Path) then
  begin
    Log('Cannot read PATH');
  end
    else
  begin
    Log(Format('PATH is %s', [Path]));
    Result := FileSearch(FileName, Path);
    if Result = '' then
    begin
      Log(Format('Cannot find %s', [FileName]));
    end
      else
    begin
      Log(Format('Found %s', [Result]));
    end;
  end;

  if Result = '' then Result := FileName; // let it fail later
end;

The above code searches only system PATH, not user PATH.

You do not need a separate installer to execute the sqlcmd.exe.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Martin Prikryl