如何在SQL中编写附加到表的触发器

时间:2012-10-26 09:00:05

标签: sql powershell smo

我想使用smo和powershell脚本来输出附加到表的触发器。

我找到了一种用触发器编写表脚本的方法,但这不是什么,我也不会总是知道触发器所连接的表的名称,我只知道触发器名称。

我想给脚本指定触发器的名称并让它编写脚本。

我一直在寻找一种方法,但没有运气。

感谢您一如既往的帮助。

2 个答案:

答案 0 :(得分:0)

这个script似乎适用于Sql Server 2008R2。您没有指定数据库,但Powershell和SMO是MS产品的有效说明。

SELECT
Tables.Name as 'TableName',
Triggers.name as 'TriggerName',
Comments.Text as 'TriggerText'
FROM  sysobjects Triggers
      Inner Join sysobjects Tables On Triggers.parent_obj = Tables.id
      Inner Join syscomments Comments On Triggers.id = Comments.id
WHERE 
      Tables.name = '<table-name>'
ORDER BY Tables.Name, Triggers.name

答案 1 :(得分:0)

以下是使用sqlps的示例:

SQLSERVER:\SQL\Z001\SQL1\Databases\pubs>$db = get-item .
SQLSERVER:\SQL\Z001\SQL1\Databases\pubs>$db.Tables | foreach {$_.Triggers} | where {$_.name -like"employee*"} | foreach {$_.Script()}

SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON

CREATE TRIGGER employee_insupd
ON employee
FOR insert, UPDATE
AS
--Get the range of level for this job type from the jobs table.
declare @min_lvl tinyint,
   @max_lvl tinyint,
   @emp_lvl tinyint,
   @job_id smallint
select @min_lvl = min_lvl,
   @max_lvl = max_lvl,
   @emp_lvl = i.job_lvl,
   @job_id = i.job_id
from employee e, jobs j, inserted i
where e.emp_id = i.emp_id AND i.job_id = j.job_id
IF (@job_id = 1) and (@emp_lvl <> 10)
begin
   raiserror ('Job id 1 expects the default level of 10.',16,1)
   ROLLBACK TRANSACTION
end
ELSE
IF NOT (@emp_lvl BETWEEN @min_lvl AND @max_lvl)
begin
   raiserror ('The level for job_id:%d should be between %d and %d.',
      16, 1, @job_id, @min_lvl, @max_lvl)
   ROLLBACK TRANSACTION
end