ป้ายกำกับ: Drop Columns

Batch Drop Multiple Columns in MSSQL with Safety ChecksBatch Drop Multiple Columns in MSSQL with Safety Checks

Batch dropping multiple columns in MSSQL can be efficiently managed using a script that ensures data integrity and safety. This article provides a comprehensive guide on how to create a batch script to drop multiple columns from a table in MSSQL, with safety checks to prevent data loss.

Introduction

In database management, it’s often necessary to modify table structures by dropping columns that are no longer needed. However, dropping columns without proper checks can lead to data loss or errors. This article will guide you through creating a batch script in MSSQL that safely drops multiple columns from a specified table.

Configuration and Setup

Before proceeding, ensure you have the necessary permissions to alter the table. The script will first check if the table exists and then proceed to drop the specified columns.

Script Implementation

The script will use a combination of SQL commands and control structures to safely drop columns. Here’s a step-by-step breakdown of the script:

SQL

-- USE DB_DEV; -- Uncomment and specify your database if needed

-- 1. Configuration
DECLARE @SchemaName AS NVARCHAR(128) = N'PItt';
DECLARE @TableName AS NVARCHAR(128) = N'Phunsanit';

-- 2. Stop script if column not null and empty
DECLARE @StopScript BIT = 0; -- flag to stop the script

-- 3. Variables for the script
DECLARE @FullTableName NVARCHAR(257);
DECLARE @TableObjectID INT;
DECLARE @CurrentColumnName NVARCHAR(128);
DECLARE @SqlStatement NVARCHAR(MAX);
DECLARE @HasData BIT = 0;
DECLARE @CheckSql NVARCHAR(MAX);
DECLARE @CheckParams NVARCHAR(100) = N'@HasData BIT OUTPUT';
DECLARE @DataTypeName NVARCHAR(128); -- <-- NEW: To store the column's data type

-- 4. Define the list of columns you want to drop
DECLARE @ColumnsToDrop TABLE (
    ColumnName NVARCHAR(128) PRIMARY KEY
);

INSERT INTO @ColumnsToDrop (ColumnName)
VALUES
    (N'created_at'),
    (N'created_by'),
    (N'deleted_at'),
    (N'deleted_by'),
    (N'updated_at'),
    (N'updated_by'),

-- 5. Store the actual commands to run (if checks pass)
DECLARE @CommandsToRun TABLE (
    SqlStatement NVARCHAR(MAX),
    ColumnName NVARCHAR(128)
);

-- 6. Safety Check: Stop if the table itself doesn't exist
SET @FullTableName = QUOTENAME(@SchemaName) + '.' + QUOTENAME(@TableName);
SET @TableObjectID = OBJECT_ID(@FullTableName);

IF @TableObjectID IS NULL
BEGIN
    PRINT 'Error: The table ' + @FullTableName + ' does not exist. Halting script.';
    RETURN; -- Stops the script
END

PRINT '--- PRE-CHECK ---';
PRINT 'Checking columns on table: ' + @FullTableName;

-- 7. Create a cursor to loop through and check each column
DECLARE col_cursor CURSOR FOR
SELECT ColumnName FROM @ColumnsToDrop;

OPEN col_cursor;

FETCH NEXT FROM col_cursor INTO @CurrentColumnName;

-- 8. First Loop (Pre-Check)
WHILE @@FETCH_STATUS = 0
BEGIN
    SET @HasData = 0; -- Reset flag for each column

    -- Check if the column exists on this specific table
    IF EXISTS (SELECT 1
               FROM sys.columns c
               WHERE c.object_id = @TableObjectID
                 AND c.name = @CurrentColumnName)
    BEGIN

        -- *** MODIFIED BLOCK ***
        -- First, get the column's data type
        SELECT @DataTypeName = ty.name
        FROM sys.columns c
        JOIN sys.types ty ON c.user_type_id = ty.user_type_id
        WHERE c.object_id = @TableObjectID
          AND c.name = @CurrentColumnName;

        -- Now build the data check SQL based on the type
        IF @DataTypeName IN (N'varchar', N'nvarchar', N'char', N'nchar', N'text', N'ntext')
        BEGIN
            -- For string types, check for NOT NULL AND not empty string (your request)
            -- This means NULLs or '' (empty strings) are OK to drop

            -- Build the check SQL statement
            SET @CheckSql = N'SELECT @HasData = CASE WHEN EXISTS (SELECT 1 FROM ' + @FullTableName + ' WHERE ' + QUOTENAME(@CurrentColumnName) + ' IS NOT NULL AND ' + QUOTENAME(@CurrentColumnName) + ' <> '''') THEN 1 ELSE 0 END';

            -- Execute the check SQL statement
            EXEC sp_executesql @CheckSql, @CheckParams, @HasData OUTPUT;

            -- If data exists, set the stop flag
            IF @HasData = 1
            BEGIN
                PRINT 'Error: Column ' + @CurrentColumnName + ' contains data. Halting script.';
                SET @StopScript = 1;
                BREAK;
            END
        END
        ELSE
        BEGIN
            -- For non-string types, check for NOT NULL
            -- Build the check SQL statement
            SET @CheckSql = N'SELECT @HasData = CASE WHEN EXISTS (SELECT 1 FROM ' + @FullTableName + ' WHERE ' + QUOTENAME(@CurrentColumnName) + ' IS NOT NULL) THEN 1 ELSE 0 END';

            -- Execute the check SQL statement
            EXEC sp_executesql @CheckSql, @CheckParams, @HasData OUTPUT;

            -- If data exists, set the stop flag
            IF @HasData = 1
            BEGIN
                PRINT 'Error: Column ' + @CurrentColumnName + ' contains data. Halting script.';
                SET @StopScript = 1;
                BREAK;
            END
        END
    END
    ELSE
    BEGIN
        PRINT 'Warning: Column ' + @CurrentColumnName + ' does not exist in table ' + @FullTableName + '.';
    END

    FETCH NEXT FROM col_cursor INTO @CurrentColumnName;
END

CLOSE col_cursor;
DEALLOCATE col_cursor;

-- If no data exists in any of the columns, proceed to drop them
IF @StopScript = 0
BEGIN
    PRINT '--- DROPPING COLUMNS ---';

    -- Create a cursor to loop through and drop each column
    DECLARE drop_cursor CURSOR FOR
    SELECT ColumnName FROM @ColumnsToDrop;

    OPEN drop_cursor;

    FETCH NEXT FROM drop_cursor INTO @CurrentColumnName;

    -- Second Loop (Drop Columns)
    WHILE @@FETCH_STATUS = 0
    BEGIN
        -- Build the drop column SQL statement
        SET @SqlStatement = N'ALTER TABLE ' + @FullTableName + ' DROP COLUMN ' + QUOTENAME(@CurrentColumnName);

        -- Execute the drop column SQL statement
        EXEC sp_executesql @SqlStatement;

        PRINT 'Dropped column: ' + @CurrentColumnName;

        FETCH NEXT FROM drop_cursor INTO @CurrentColumnName;
    END

    CLOSE drop_cursor;
    DEALLOCATE drop_cursor;

    PRINT 'All specified columns have been dropped successfully.';
END
ELSE
BEGIN
    PRINT 'Script halted due to data in one or more columns.';
END

Conclusion

This script provides a safe and efficient way to drop multiple columns from a table in MSSQL. By checking for data in each column before dropping it, the script ensures that no data is accidentally lost. This is particularly useful in production environments where data integrity is critical.