8

I have SQL Server 2008 R2. I have around 150 tables in a database and for each table I have recently created triggers. It is working fine in my local environment.

Now I want to deploy them on my live environment. The question is I want to deploy only the triggers. I tried the Generate Script wizard but it is creating script with table schema along with triggers, NOT triggers only.

Is there anyway to generate all the triggers drop and create type script?

marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
Dev
  • 6,570
  • 10
  • 66
  • 112

2 Answers2

11

Forget the wizard. I think you have to get your hands dirty with code. Script below prints all triggers code and stores it into table. Just copy the script's print output or get it from #triggerFullText.

USE YourDatabaseName
GO
SET NOCOUNT ON;

CREATE TABLE #triggerFullText ([TriggerName] VARCHAR(500), [Text] VARCHAR(MAX))
CREATE TABLE #triggerLines ([Text] VARCHAR(MAX))

DECLARE @triggerName VARCHAR(500)
DECLARE @fullText VARCHAR(MAX)

SELECT @triggerName = MIN(name)
FROM sys.triggers

WHILE @triggerName IS NOT NULL
BEGIN
    INSERT INTO #triggerLines 
    EXEC sp_helptext @triggerName

    --sp_helptext gives us one row per trigger line
    --here we join lines into one variable
    SELECT @fullText = ISNULL(@fullText, '') + CHAR(10) + [TEXT]
    FROM #triggerLines

    --adding "GO" for ease of copy paste execution
    SET @fullText = @fullText + CHAR(10) + 'GO' + CHAR(10)

    PRINT @fullText

    --accumulating result for future manipulations
    INSERT INTO #triggerFullText([TriggerName], [Text])
    VALUES(@triggerName, @fullText)

    --iterating over next trigger
    SELECT @triggerName = MIN(name)
    FROM sys.triggers
    WHERE name > @triggerName

    SET @fullText = NULL

    TRUNCATE TABLE #triggerLines
END

DROP TABLE #triggerFullText
DROP TABLE #triggerLines
AHiggins
  • 7,029
  • 6
  • 36
  • 54
pkmiec
  • 2,594
  • 18
  • 16
  • 1
    Thanks. Although I had resolved my issue different way, your solution is better to be used. Thanks a lot :) – Dev Jan 06 '14 at 11:08
0

Just in generate scripts wizard in the second step ("Set Scripting Options) press Advanced button=> Table/View Options=> Set Script Triggers to True. check also this link or this. If you want only triggers just select one table to proceed the next step.

kostas ch.
  • 1,960
  • 1
  • 17
  • 30