SQL Server How to create trigger after alter table that makes copy of added column with suffix _vis to another table?

ulydmbyx  于 2023-08-02  发布在  其他
关注(0)|答案(1)|浏览(87)

Hello I feel really stuck because i don't code in SQL that often,

I have two tables one is Subproject and SubprojectVisibilitySettings

Example columns in tables

Table Subproject - SubprojectId | SubprojectName | SubprojectType

Table SubprojectVisibilitySettings - UserName | SubprojectId_vis | SubprojectName_Vis | SubprojectType_Vis

I need to make a trigger that checks if new column was added to Subproject table if yes then also add the column with the same name + suffix "_Vis" to table SubprojectVisibilitySettings table.

Expected result

Table Subproject - SubprojectId | SubprojectName | SubprojectType | SubprojectDate

Table SubprojectVisibilitySettings - UserName | SubprojectId_vis | SubprojectName_Vis | SubprojectType_Vis | SuprojectDate_Vis

If someone would help me to solve this I would be really thankful.

ru9i0ody

ru9i0ody1#

I found one way to create trigger for my needs I don't know if its good solution but works for me. So if someone struggles like me just try this.

Creating the trigger

SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TRIGGER [AddColumnTrigger]
ON DATABASE
FOR ALTER_TABLE
AS
BEGIN
    -- Check if the target table is Subproject
    IF EVENTDATA().value('(/EVENT_INSTANCE/ObjectName)[1]', 'NVARCHAR(128)') = 'Subproject'
    BEGIN
        
        DECLARE @columnName NVARCHAR(128) -- the added column name

        SELECT TOP 1 @columnName = COLUMN_NAME
        FROM INFORMATION_SCHEMA.COLUMNS
        WHERE TABLE_NAME = 'Subproject'
            AND COLUMN_NAME NOT IN (
                SELECT REPLACE(name, '_Vis', '')
                FROM sys.columns
                WHERE object_id = OBJECT_ID('SubprojectVisibility')
            )
        ORDER BY ORDINAL_POSITION DESC

        -- Check if the column exists and is not present in SubprojectVisibility
        IF @columnName IS NOT NULL AND NOT EXISTS (
            SELECT 1
            FROM sys.columns
            WHERE object_id = OBJECT_ID('SubprojectVisibility')
                AND name = @columnName + '_Vis'
        )
        BEGIN
            DECLARE @sql NVARCHAR(MAX)
            SET @sql = N'
                ALTER TABLE SubprojectVisibility
                ADD ' + QUOTENAME(@columnName + '_Vis') + ' TINYINT NOT NULL DEFAULT (0);
            '
-- replace TINYINT with desired dataType and value
            EXEC sp_executesql @sql
        END
    END
END
GO
ENABLE TRIGGER [AddColumnTrigger] ON DATABASE
GO

Alter table Subproject adding new column

ALTER TABLE dbo.Subproject
ADD NewExampleColumn int;

The result

Subproject 

SubprojectId | SubprojectName | NewExampleColumn

SubprojectVisibility

SubprojectId_vis | SubprojectName_Vis |  NewExampleColumn_Vis

相关问题