1

I am using the below code get completed code of triggers in the selected database.

select [definition] +' ' + 'GO' 
from sys.sql_modules m
inner join sys.objects obj on obj.object_id=m.object_id
where obj.type ='TR'

Requirement: I would like to export the above trigger code as C:\TMP\Trigger.sql with help of T-SQL coding instead of Generate scripts using script wizard. I am not so strong in SQL Server. Can someone help me with this?

2
  • you could use the results to file option in ssms and mostly you will be fine, dont have an server to test currently,but i dont see an issue with your script Commented Apr 23, 2017 at 11:50
  • my requirement is I need to export results as .sql which can be integrated as job in sql which will run on different instance so I can go depend on GUI Commented Apr 23, 2017 at 11:59

1 Answer 1

1

To schedule the scripting via a batch job, consider using a Powershell script or SSIS. Powershell script example:

try {

    Add-Type -Path "C:\Program Files\Microsoft SQL Server\130\SDK\Assemblies\Microsoft.SqlServer.Smo.dll";

    $databaseName = "AdventureWorks2014";
    $sqlServerName = ".";
    $scriptPath = "c:\Scripts\TriggerScripts.sql";

    $SMOserver = New-Object Microsoft.SqlServer.Management.Smo.Server($sqlServerName);
    $scriptr = new-object ('Microsoft.SqlServer.Management.Smo.Scripter') ($SMOserver);

    If (Test-Path $scriptPath) {
        Remove-Item $scriptPath;
    }

    $database = $SMOserver.databases[$databaseName]

    $objectsToScript = @();

    foreach($table in $database.Tables) {
        $objectsToScript += $table.Triggers;
    }

    $scriptr.Options.FileName = $scriptPath;
    $scriptr.Options.AnsiFile = $false;
    $scriptr.Options.AllowSystemObjects = $false;
    $scriptr.Options.IncludeIfNotExists = $false;
    $scriptr.Options.NoCommandTerminator = $false;
    $scriptr.Options.ScriptBatchTerminator = $true;

    $null = $scriptr.Script($objectsToScript);

}
catch [Exception] {
    $e = $_.Exception
    $e.ToString();
    throw;
}
Sign up to request clarification or add additional context in comments.

2 Comments

Thanks Dan . Is there any way to simplify and use T-SQL code or PROCEEDURE instead of PS hence PS is restricted on our prod envt.
The tricky part of a T-SQL only solution is creating the file. How would you do that in T-SQL? If your organization has locked down Powershell, I would expect creating files in T-SQL to be an absolute no-no. Maybe SSIS is acceptable middle ground.

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.