我需要在不知道主键列名称的情况下更新DateModified列。
基本上,我有一个像这样简单的UPDATE触发器:
CREATE TRIGGER updated_SCHEMA_TABLE
ON [SCHEMA].[TABLE]
AFTER UPDATE AS
BEGIN
SET NOCOUNT ON;
UPDATE [SCHEMA].[TABLE]
SET DateModified = getdate()
WHERE [PRIMARYKEY]
IN (SELECT [PRIMARYKEY]
FROM Inserted)
END
但不知道主键的列名,因为触发器将以编程方式生成(see this question as to why)。
这可能吗?
答案 0 :(得分:2)
这适用于具有单列PK的表。从这些开始可能是最简单的,然后返回并使用复合PK手动调整它们。
select 'create trigger updated_'+s.name + '_' + t.name + ' on ' + quotename(s.name) + '.' + quotename(t.name)
+ ' after update as'
+ ' begin '
+ ' set nocount on; '
+ ' update t'
+ ' set [DateModified] = getdate()'
+ ' from inserted i'
+ ' inner join ' + quotename(s.name) + '.' + quotename(t.name) + ' t'
+ ' on i.' + quotename(c2.name) + ' = t.' + quotename(c2.name)
+ ' end'
from sys.columns c
inner join sys.tables t
on c.object_id = t.object_id
inner join sys.schemas s
on t.schema_id = s.schema_id
inner join sys.indexes i
on t.object_id = i.object_id
inner join sys.index_columns ic
on i.object_id = ic.object_id
and i.index_id = ic.index_id
inner join sys.columns c2
on ic.object_id = c2.object_id
and ic.index_id = c2.column_id
where c.name = 'DateModified'
and t.type = 'U'
and i.is_primary_key = 1
答案 1 :(得分:1)
如果您能够从标识列构建所有主键:
SELECT table_name, column_name
FROM INFORMATION_SCHEMA.COLUMNS
where COLUMNPROPERTY (OBJECT_ID(Table_Name),Column_Name,'IsIdentity') = 1
and table_schema = [SCHEMA] and table_name = [TABLE]
否则,您将不得不使用所有sys表(好工作Joe)查看索引。
答案 2 :(得分:0)
好吧,我刚刚通过一些系统视图快速浏览了一下,我没有看到任何告诉你每个表的主键是什么。你可能需要手工完成。