我正在使用以下代码在所选数据库中获取完成的触发器代码。
select [definition] +' ' + 'GO'
from sys.sql_modules m
inner join sys.objects obj on obj.object_id=m.object_id
where obj.type ='TR'
要求:我想借助T-SQL编码将上述触发器代码导出为C:\TMP\Trigger.sql
,而不是使用脚本向导生成脚本。我在SQL Server中不是那么强大。有人可以帮我这个吗?
答案 0 :(得分:1)
要通过批处理作业安排脚本编制,请考虑使用Powershell脚本或SSIS。 Powershell脚本示例:
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;
}