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

huangapple go评论62阅读模式
英文:

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

问题

你好,我感到非常困惑,因为我不经常编写SQL代码,

我有两个表,一个是Subproject,另一个是SubprojectVisibilitySettings

表中的示例列

Subproject表 - SubprojectId | SubprojectName | SubprojectType

SubprojectVisibilitySettings表 - UserName | SubprojectId_vis | SubprojectName_Vis | SubprojectType_Vis

我需要创建一个触发器,检查是否向Subproject表添加了新列,如果是的话,还需要将具有相同名称+后缀 "_Vis" 的列添加到SubprojectVisibilitySettings表中。

预期结果

Subproject表 - SubprojectId | SubprojectName | SubprojectType | SubprojectDate

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

如果有人能帮助我解决这个问题,我将不胜感激。

英文:

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.

答案1

得分: 1

我找到了一种满足我的需求的创建触发器的方法,不知道是否是一个好的解决方案,但对我来说有效。所以如果有人和我一样遇到困难,可以尝试这个。

创建触发器

    SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TRIGGER [AddColumnTrigger]
ON DATABASE
FOR ALTER_TABLE
AS
BEGIN
    -- 检查目标表是否为Subproject
    IF EVENTDATA().value('(/EVENT_INSTANCE/ObjectName)[1]', 'NVARCHAR(128)') = 'Subproject'
    BEGIN
        
        DECLARE @columnName NVARCHAR(128) -- 新添加的列名

        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

        -- 检查列是否存在且不存在于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);
            ';
-- 用所需的数据类型和值替换TINYINT
            EXEC sp_executesql @sql
        END
    END
END
GO
ENABLE TRIGGER [AddColumnTrigger] ON DATABASE
GO

修改表Subproject以添加新列

ALTER TABLE dbo.Subproject
ADD NewExampleColumn int;

结果

Subproject 

SubprojectId | SubprojectName | NewExampleColumn

SubprojectVisibility

SubprojectId_vis | SubprojectName_Vis |  NewExampleColumn_Vis
英文:

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

huangapple
  • 本文由 发表于 2023年7月6日 22:15:11
  • 转载请务必保留本文链接:https://go.coder-hub.com/76629766.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定