[Webinar] Streamline your web hosting managementRegister Today

x
  • Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 1368
  • Last Modified:

Schema Binding for a Trigger

I have an INSTEAD OF INSERT trigger that must be updated anytime the underlying table is, but I can't add schema binding to the trigger. Is there an alternative?
0
elmoredaniel
Asked:
elmoredaniel
  • 3
1 Solution
 
maradamCommented:
Yes. DDL Trigger is this alternative. You can create trigger on database for alter table statement. In this trigger you can implement your logic. For example set a status for your table stating that it was altered, and check this status first in your instead of trigger and raise an error if the status is not ok. The status can be implemented via extended property.
0
 
elmoredanielAuthor Commented:
hey i don't quite follow your solution, can you show some code as an example, thanks
0
 
maradamCommented:
OK. Maybe my solution was unnessesairly too complex. I will try to show you how to make it work exactly like schemabinding works. It will disallow to alter the table while trigger exists. Table and trigger names hardcoded for simplicity but you can still make it more elegant by creating a table with schema bound triggers.
create table mycoolTable(a int)
GO
CREATE TRIGGER DDLTR_SchemaBindTrigger
ON DATABASE
FOR ALTER_TABLE 
AS
BEGIN
  SET NOCOUNT ON
  declare @E xml
  set @E = eventdata()
  declare @TableName sysname
  SELECT @TableName =    @E.value('(/EVENT_INSTANCE/ObjectName)[1]','nvarchar(128)')
  IF @TableName = 'myCoolTable' AND EXISTS (SELECT * FROM sys.triggers t WHERE t.name = 'myCoolInsteadOfTrigger') BEGIN
    RAISERROR ('Could not alter table %s, because trigger %s exists. Drop the trigger first, then alter the table and recreate the trigger',
      16,1,@TableName,'myCoolInsteadOfTrigger') 
    ROLLBACK
  END   
END
GO
alter table myCoolTable add b int -- this will work. No trigger
GO
create trigger myCoolInsteadOfTrigger
on myCoolTable instead of insert
as
print 'here I am'
GO
alter table myCoolTable add c int -- this will return the error
GO
DROP TRIGGER myCoolTrigger
GO
alter table myCoolTable add c int -- will work again :)
GO

Open in new window

0
 
maradamCommented:
Correction:

DROP TRIGGER myCoolInsteadOfTrigger
0

Featured Post

Take Control of Web Hosting For Your Clients

As a web developer or IT admin, successfully managing multiple client accounts can be challenging. In this webinar we will look at the tools provided by Media Temple and Plesk to make managing your clients’ hosting easier.

  • 3
Tackle projects and never again get stuck behind a technical roadblock.
Join Now