Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SQL SERVER 2008 TRIGGER ON CREATE TABLE

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

like image 499
themhz Avatar asked Jul 22 '26 14:07

themhz


2 Answers

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.

like image 110
Aaron Bertrand Avatar answered Jul 25 '26 03:07

Aaron Bertrand


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
like image 25
TyT Avatar answered Jul 25 '26 04:07

TyT



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!