5

Is it possible, in a script executed in MS SQL Server 2005, to copy a trigger from one database to another?

I've been asked to write a test script for a trigger my project is using. Our test structure is to create an empty database containing only the object under test, then execute a script on that database that creates all the other objects needed for the test, fills them, runs whatever tests are needed, compares the results against expected results, and then drops everything except the object under test.

I can't just create a database that is empty except for the trigger, because the trigger depends on several tables. My test script currently runs the CREATE TRIGGER after all the required tables are created, but this won't do because the test script isn't allowed to contain the object under test.

What's been suggested is that, instead of running a CREATE TRIGGER, I somehow copy the trigger at that point in the script from the live database to the test database. I've had a quick Google and haven't found a way to do this. Thus my question - is this even possible, and if so, how can I do it?

2 Answers 2

2

You could read the text of the trigger with sp_helptext (triggername)

Or you can select the text into a variable and execute that:

declare @sql varchar(8000)


select @sql = object_definition(object_id) 
from sys.triggers
where name = 'testtrigger'

EXEC @sql
1
  • Thanks, that's brilliant. With a few USEs and EXEC (@sql) this is doing exactly what I want.
    – Rawling
    Nov 27, 2009 at 10:27
0

I have a stored procedure that copies a bunch of tables to a test database. To make it less prone to mistakes that could potentially change the wrong database, I want to avoid using USE and instead explicitly specify per statement which database the trigger is copied from and to.

With the help of this answer, I came up with this solution:

DECLARE @sql NVARCHAR(MAX);
EXEC SourceDB.sys.sp_executesql
    N'SELECT @output = (SELECT OBJECT_DEFINITION(OBJECT_ID(''TriggerName'')))',
    N'@output VARCHAR(MAX) OUTPUT',
    @output = @sql OUTPUT;
EXEC DestDB.sys.sp_executesql @sql;

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.