前几天我们发现了一个包含ModifiedDate
列的表,但发现没有触发器来实际更新该列。现在我正在尝试编写一个脚本来查找所有具有ModifiedDate
列但没有触发器来更新它的表。
以下是我目前的情况:
SELECT so.name AS 'TableName', sc.name AS 'ColumnName', tr.name AS 'Trigger'
FROM sys.objects so
INNER JOIN sys.columns sc ON sc.object_id = so.object_id
LEFT JOIN sys.triggers tr ON so.object_id=tr.object_id
WHERE so.type = 'U' AND sc.name LIKE '%ModifiedDate%'
AND tr.type = 'TR'
首先,我想找到同时包含列和触发器的所有表。我能够找到包含ModifiedDate
列的所有表格,但是当我添加最后一个过滤器AND tr.type = 'TR'
时,它什么也没有返回。我检查过那里有桌子,里面有我正在寻找的列和触发器,所以我希望看到列表中的那些。
答案 0 :(得分:2)
SELECT so.name AS 'TableName', sc.name AS 'ColumnName', tr.name AS 'Trigger'
FROM sys.objects so
INNER JOIN sys.columns sc ON sc.object_id = so.object_id
LEFT JOIN sys.triggers tr ON so.object_id=tr.parent_id
WHERE so.type = 'U' AND sc.name LIKE '%ModifiedDate%'
AND tr.type = 'TR'
您在“触发器”上的连接错误
清理您的查询,找到所有没有触发器的表格:
Select t.name As 'TableName'
,c.name As 'ColumnName'
,tr.name As 'Trigger'
From sys.tables t
Join sys.columns c On c.object_id = t.object_id
Left Join sys.triggers tr On t.object_id = tr.parent_id
Where c.name Like '%ModifiedDate%'
And tr.name Is Null
我拿出了一些多余的东西。对表进行选择无需查找Type ='U',而parent_id \ object_id关系也不需要使用Type ='TR'子句强制执行它。