You are creating an elastic job. One job step creates a table named dbo.AuditLog in every database in a target group. Some databases might already contain dbo.AuditLog, with rows written by an earlier run. The step must be safe to run more than once against the same database without errors, and it must not remove existing rows.
Which T-SQL should you use for the job step?
Elastic job scripts should be idempotent so that repeating a successful step preserves its intended result. Jobs can be repeated accidentally or retried after a failure. Checking for the table before creating it makes this step repeatable while preserving existing rows. Dropping or truncating the existing table would remove those rows.
- Not correct:
CREATE TABLE dbo.AuditLog (Id int NOT NULL);. There is no existence check. A second run against a database that already has the table fails, so the script is not idempotent. - Not correct:
IF OBJECT_ID(N'dbo.AuditLog', N'U') IS NOT NULL TRUNCATE TABLE dbo.AuditLog ELSE CREATE TABLE dbo.AuditLog (Id int NOT NULL);. The script avoids an error on a repeat run, but it truncates the existing table and deletes its rows. That breaks the requirement to keep existing data. - Not correct:
DROP TABLE IF EXISTS dbo.AuditLog; CREATE TABLE dbo.AuditLog (Id int NOT NULL);. The script drops the existing table and its rows before recreating it. That violates the requirement to preserve existing rows. - Correct:
IF OBJECT_ID(N'dbo.AuditLog', N'U') IS NULL CREATE TABLE dbo.AuditLog (Id int NOT NULL);. The script creates the table only when it does not exist and leaves existing rows unchanged.