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
RETURN someValue
maybe? AlternativelyTHROW
instead ofRAISERROR