SQL SERVER 2008 TRIGGER ON CREATE TABLE

2020-04-14 03:05发布

Is there a way to run some function like a trigger when a table is created in the database in SQL SERVER 2008?

2条回答
我想做一个坏孩纸
2楼-- · 2020-04-14 03:31

Yes, it's called a DDL trigger. The documentation for CREATE TRIGGER has a sample for DROP_SYNONYM (a very questionable choice for an example) but you'll want the CREATE_TABLE event instead. A better starting point in understanding how they work is probably here:

http://msdn.microsoft.com/en-us/library/ms190989.aspx

If you have more specific details, e.g. what exactly do you want to pass to this function (I assume you mean procedure), or what does the procedure do, we can provide more useful and specific help.

查看更多
姐就是有狂的资本
3楼-- · 2020-04-14 03:38

Yes a DDL Trigger. For example, here is some code I written to prevent some tables from being modified:

PRINT N'Create DDL trigger to prevent changes to various tables'
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TRIGGER NoEditCertainTables ON DATABASE 
    FOR DROP_TABLE, ALTER_TABLE, CREATE_TABLE
AS 

SET CONCAT_NULL_YIELDS_NULL ON

DECLARE @AffectedTable varchar(255) 
SELECT  @AffectedTable = EVENTDATA().value('(/EVENT_INSTANCE/ObjectName)[1]','nvarchar(100)') 

--This is the name of the table(s) you dont want messed with
IF (@AffectedTable IN ('Table1','Table2','Table3'))
BEGIN
    ROLLBACK;
END 
SET CONCAT_NULL_YIELDS_NULL OFF      

GO
查看更多
登录 后发表回答