I have following two statements executing triggers:
IF EXISTS (SELECT * FROM sys.triggers
WHERE Object_ID = Object_ID("Insert_Serverdate_Into_CreatedAt"))
DROP TRIGGER Insert_Serverdate_Into_CreatedAt
GO
CREATE TRIGGER Insert_Serverdate_Into_CreatedAt ON *myTable*
AFTER INSERT
AS
BEGIN
INSERT INTO *myTable* (CreatedAt) VALUES(GETDATE())
END
GO
IF EXISTS (SELECT * FROM sys.triggers
WHERE Object_ID = Object_ID("Insert_Serverdate_Into_UpdatedAt"))
DROP TRIGGER Insert_Serverdate_Into_UpdatedAt
GO
CREATE TRIGGER Insert_Serverdate_Into_UpdatedAt ON *myTable*
AFTER UPDATE
AS
BEGIN
INSERT INTO *myTable* (UpdatedAt) VALUES(GETDATE())
END
GO
Now I have found two possibilities to loop through each table in my database The first one is:
EXECUTE sp_MSforeachtable @command1 = myCommand
The second one is:
DECLARE @NAME VARCHAR(100)
DECLARE @SQL NVARCHAR(300)
DECLARE CUR CURSOR FOR
SELECT NAME
FROM SYS.TABLES
WHERE TYPE = 'U'
AND SCHEMA_ID = 1
OPEN CUR
FETCH NEXT FROM CUR INTO @NAME
WHILE @@FETCH_STATUS = 0
BEGIN
SET @SQL = myCommand
PRINT @SQL
EXEC Sp_executesql
@SQL
FETCH NEXT FROM CUR INTO @NAME
END
CLOSE CUR
DEALLOCATE CUR
The problem here is that these possibilities do not know the keyword GO
which I need for executing my commands.
Is there a possibility to loop through all tables and execute my statement?
Thank you!