1

I am executing some sql queries using OSQL through inno setup. I am using following code to run OSQL. This is just for example purpose

SQLQuery:= '"EXEC sp_addserver ''PCNAME'';"';
Param:= '-S(local) -Usa -Psa -Q ' + SQLQuery;
Exec('osql.exe', Param, '', SW_HIDE, ewWaitUntilTerminated, ResultCode);

This works fine. The problem is ResultCode value is always 0. Even if the query does not get executed. For example if I try same query like below where I pass in an invalid stored procedure name the ResultCode is still 0.

SQLQuery:= '"EXEC sp_invalidname ''PCNAME'';"';
Param:= '-S(local) -Usa -Psa -Q ' + SQLQuery;
Exec('osql.exe', Param, '', SW_HIDE, ewWaitUntilTerminated, ResultCode);

Why don't this return me a proper code. If I run the second query in management studio I get an error like this

Msg 2812, Level 16, State 62, Line 1 Could not find stored procedure 'sp_invalidname'

Here return code is 2812. Why dont I get this when I run it through inno. What do I need to do to get this error code in inno?

Newbee
  • 1,379
  • 2
  • 16
  • 36

1 Answers1

2

Thanks to TLama, I updated my code as below and its working now. I had to add -b command line parameter and now it returns 1 if the command fails.

-b Specifies that osql exits and returns a DOS ERRORLEVEL value when an error occurs. The value returned to the DOS ERRORLEVEL variable is 1 when the SQL Server error message has a severity of 11 or greater; otherwise, the value returned is 0. Microsoft MS-DOS batch files can test the value of DOS ERRORLEVEL and handle the error appropriately.

I updated my code as below.

Param:= '-S(local) -Usa -Psa -b -Q ' + SQLQuery;

Its explained in the documentation.

Newbee
  • 1,379
  • 2
  • 16
  • 36