当我们在表格中插入或更新数据时,我希望主键和表格名称插入到另一个表格中。
我需要在一天结束时协调所有今天更新的表格。
请建议。谢谢。
答案 0 :(得分:3)
看看CDC - Change Data Capture
或保罗尼尔森的AutoAudit。
答案 1 :(得分:0)
SELECT name
FROM sys.objects
WHERE DATEDIFF(D,modify_date, GETDATE()) < 1
通过使用此查询,您可以获得数据库的所有修改。代替1,你可以不给你想要看到变化的日子。
答案 2 :(得分:0)
我已经找到了类似的东西...我希望它能回答你的问题。
CREATE TABLE [dbo].[log_table]( [table_name] [varchar](1000) NULL, [column_name] [varchar](1000) NULL, [column_value] [varchar](1000) NULL, [datetime] [datetime] NULL ) GO
CREATE TABLE [dbo].[Animals](
[AnimalID] [int] IDENTITY(1,1) NOT NULL,
[AnimalName] [varchar](50) NULL,
CONSTRAINT [PK_Animals] PRIMARY KEY CLUSTERED
([AnimalID] ASC)
)
GO
CREATE TABLE [dbo].[Countries](
[CountryID] [uniqueidentifier] NOT NULL,
[CountryName] [varchar](50) NULL,
CONSTRAINT [PK_Countries] PRIMARY KEY CLUSTERED
([CountryID] ASC))
ALTER TABLE [dbo].[Countries] ADD CONSTRAINT [DF_Countries_countryID] DEFAULT (newid()) FOR [CountryID]
GO
SELECT ' IF OBJECT_ID ('+ CHAR(39) + SCHEMA_NAME(tbl.SCHEMA_ID) + '.trg_' + tbl.name + CHAR(39) + ',''TR'') IS NOT NULL ' + ' DROP TRIGGER ' + SCHEMA_NAME(tbl.SCHEMA_ID) + '.trg_'+ tbl.name + ';' + ' EXEC (' + CHAR(39) + ' CREATE TRIGGER ' + SCHEMA_NAME(tbl.SCHEMA_ID) + '.trg_'+ tbl.name + ' ON '+ SCHEMA_NAME(tbl.SCHEMA_ID) + '.' + tbl.name + ' FOR INSERT,UPDATE AS ' + ' DECLARE @newval varchar(1000) ' + ' SELECT @newval ='+ COL_NAME(tbl.object_id, ic.column_id) + ' FROM INSERTED' + ' INSERT INTO log_table(table_name,column_name,column_value,datetime) VALUES('+ CHAR(39)+ CHAR(39) + SCHEMA_NAME(tbl.SCHEMA_ID) +'.'+ tbl.name + CHAR(39)+ CHAR(39) + ' ,'+ CHAR(39)+ CHAR(39) + COL_NAME(tbl.object_id, ic.column_id) + CHAR(39)+ CHAR(39) + ' ,'+ '@newval,getdate()'+ ')' + CHAR(39)+ ')' FROM sys.tables AS tbl INNER JOIN sys.key_constraints AS kc ON kc.parent_object_id = tbl.object_id INNER JOIN sys.indexes AS i ON kc.unique_index_id = i.index_id AND kc.parent_object_id = i.object_id INNER JOIN sys.index_columns AS ic ON i.object_id = ic.object_id AND i.index_id = ic.index_id WHERE tbl.type = 'U' AND ic.is_included_column = 0 and tbl.name NOT IN ('sysdiagrams','log_table') ORDER BY tbl.object_id, ic.key_ordinal;
现在插入我们的表格
INSERT INTO Countries(CountryName) VALUES('South Africa') INSERT INTO Countries(CountryName) VALUES('USA') INSERT INTO Countries(CountryName) VALUES('Brazil') INSERT INTO Countries(CountryName) VALUES('Zimbabwe') INSERT INTO Countries(CountryName) VALUES('Africa is not a country') INSERT INTO Animals(AnimalName) VALUES ('Lion') INSERT INTO Animals(AnimalName) VALUES ('African Elephant') INSERT INTO Animals(AnimalName) VALUES ('Rhinoceros') INSERT INTO Animals(AnimalName) VALUES ('Leopard') INSERT INTO Animals(AnimalName) VALUES ('Cape Buffalo')