HiveBrain v1.2.0
Get Started
← Back to all entries
snippetsqlMinor

How to set the sqlcmd.exe exit code?

Submitted by: @import:stackexchange-dba··
0
Viewed 0 times
exetheexitsqlcmdhowcodeset

Problem

The script needs to test to see if a backup table already exists and stop if it does. This is to prevent overwriting a backup already created.

The following will stop further script execution (but not interpretation output). However, it does not set the exit code value. It needs to set the exit code value in order to support automation.

This needs to work even if the user is not sysadmin. Therefore, RAISEERROR() with a severity code > 18 and WITH LOG does not improve the situation.

The script needs to work in both sqlcmd.exe and SSMS on SQL Server as early as 2012.

IF EXISTS (SELECT 1 FROM BUDB.INFORMATION_SCHEMA.TABLES
    WHERE TABLE_SCHEMA = 'dbo' AND TABLE_NAME = 'TABLE_A')
BEGIN
    PRINT 'ERROR: Table BUDB.dbo.TABLE_A already exists.'
    RAISERROR('ERROR: Will not create existing backup table.', 18, -1);
    SET NOEXEC ON;
END

IF EXISTS (SELECT 1 FROM BUDB.INFORMATION_SCHEMA.TABLES
    WHERE TABLE_SCHEMA = 'dbo' AND TABLE_NAME = 'TABLE_B')
BEGIN
    PRINT 'ERROR: Table BUDB.dbo.TABLE_B already exists.'
    RAISERROR('ERROR: Will not create existing backup table.', 18, -1);
    SET NOEXEC ON;
END

Solution

Did you try the -b switch of sqlcmd ?
See https://learn.microsoft.com/en-us/sql/tools/sqlcmd-utility?view=sql-server-ver16#command-line-options

Context

StackExchange Database Administrators Q#314751, answer score: 3

Revisions (0)

No revisions yet.