Harold W
Harold W

Reputation: 77

Create A Trigger Automaticly Every Day

I have a MSSQL GPS database which create every month a database and every day a table. This is a real time database that getting data every 3 seconds. And all operations are making by a GPS program which I have no source code or access.

Databases looks like this :

      -Comms201502       (Database)
      -Comms201503       (Database)
      -Comms201504       (Database)
         -GPS20150401    (Database's Table)
         -GPS20150402    (Database's Table)
         -GPS20150403    (Database's Table)
         -GPS20150404    (Database's Table)
         -...

I have a trigger that receiving data from a table which I have to create that trigger for every day, and writing to my database.

Is there a anyway to create single trigger or create an automaticly create trigger every day ?

Best regards,

Upvotes: 0

Views: 1053

Answers (1)

Steve Ford
Steve Ford

Reputation: 7753

I would create a DDL trigger, this would be raised each time a CREATE TABLE Statement is executed and then adds a trigger to the new table to log the records to your table, such as:

CREATE TRIGGER trg_DDLCreateTrigger ON DATABASE 
    FOR  CREATE_TABLE
AS 
BEGIN
    SET NOCOUNT ON;
    DECLARE @EventData XML = EVENTDATA();

    DECLARE @Schema SYSNAME 
    DECLARE @TableName SYSNAME

    SELECT @Schema = EVENTDATA().value('(/EVENT_INSTANCE/SchemaName)[1]','nvarchar(max)'),
            @TableName = EVENTDATA().value('(/EVENT_INSTANCE/ObjectName)[1]','nvarchar(max)')

    DECLARE @sql VARCHAR(MAX)

    SET @sql = 'CREATE TRIGGER [trg_' + @TableName + '] ON [' + @Schema + '].[' + @TableName + ']' +
    ' AFTER INSERT AS ' +
    ' INSERT INTO MyTable SELECT * FROM inserted' --Change this as required

EXEC (@Sql)  

END
GO

You should probably add some validation in the trigger to check that the table is one that you are interested in capturing.

You can probably extend this so that there is a DDL trigger on a create database statement, which adds this trigger to the database.

Upvotes: 1

Related Questions