I'm trying to figure out how to write a trigger that will add a newly created column to another table.
Situation: I have dbo.tableA
and dbo.tableA_Archive
tables.
When I add a column to dbo.TableA
using this T-SQL:
ALTER TABLE dbo.TableA
ADD [Column72] INT NULL
I need the trigger to add the same column to the dbo.TableA_Archive
table as well.
I have not been able to find any examples that come close to doing this.
Since several commenters decided to just rag on me, and only @Bogdan Sahlean posted any thing of relevance, I'd give them credit, but they didn't post it as an answer.
Here is the final solution I came up with based on their guidance.
CREATE OR ALTER TRIGGER AlterTable
ON DATABASE
AFTER ALTER_TABLE
AS
BEGIN
DECLARE
@lv_xml_EventData XML,
@lv_vc_SQLCMD VARCHAR(MAX)
SET @lv_xml_EventData = EVENTDATA()
IF @lv_xml_EventData.value('(EVENT_INSTANCE/ObjectType)[1]','VARCHAR(200)') = 'TABLE'
BEGIN
DECLARE
@lv_vc_Table_Name VARCHAR(200) = @lv_xml_EventData.value('(EVENT_INSTANCE/ObjectName)[1]','VARCHAR(200)')
IF @lv_vc_Table_Name = 'TableA'
BEGIN
SET @lv_vc_SQLCMD = @lv_xml_EventData.value('(EVENT_INSTANCE/TSQLCommand/CommandText)[1]','VARCHAR(MAX)')
SET @lv_vc_SQLCMD = REPLACE(@lv_vc_SQLCMD,'TableA','TableA_Archive')
BEGIN TRY
EXEC (@lv_vc_SQLCMD)
END TRY
BEGIN CATCH
THROW;
ROLLBACK
END CATCH
END
END
END
Now I know there are probably better ways to do this, but it does answer my question, and meet my needs.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.