gpt4 book ai didi

sql-server - SQL Server如何监控表结构变化?

转载 作者:行者123 更新时间:2023-12-04 00:01:44 24 4
gpt4 key购买 nike

我想监控SQL Server中某个表结构的变化。

例如假设我有下表;

现有

ID,int,not null
Name,varchar, null

已更改

ID,int,not null
Name,varchar, null
Lastname, varchar, null

是否可以通过 SQL 查询知道是否有新列添加到此表中?我想具体找到新添加的列。

我试过这个;但它没有给我新添加的列名。

SELECT
OBJECT_NAME(sc.[object_id]) as [table]
,sc.[name] as [column]
,so.modify_date
,so.create_date
FROM [sys].[columns] sc
JOIN [sys].[objects] so
ON sc.[object_id] = so.[object_id]
ORDER BY so.modify_date DESC

有什么想法吗?

最佳答案

您可以在数据库上使用 ddl 触发器

create table dbo.logtablechanges
(
tableobject_id int,
tablename sysname,
columnname sysname,--log a single column alteration
theaction varchar(50),
actionbylogin sysname constraint df_logtablechanges_actionbylogin default(original_login()),
thestatement nvarchar(max),
thedate datetime constraint df_logtablechanges_thedate default(getdate())
);
go

create table dbo.guineapigtbl(id int identity);
insert into dbo.guineapigtbl default values;
select * from guineapigtbl;
go

create trigger trig_db_alter_table on database
for ALTER_TABLE
as
begin

declare @d xml = EVENTDATA();

declare @tblschemaname sysname,
@tblname sysname,
@action varchar(20),
@colname sysname,
@sqlcommand nvarchar(max);

--for multiple columns
select
@tblschemaname = @d.value('(/EVENT_INSTANCE/SchemaName)[1]', 'sysname'),
@tblname = @d.value('(/EVENT_INSTANCE/ObjectName)[1]', 'sysname'),
@action = @d.value('local-name((/EVENT_INSTANCE/AlterTableActionList/*)[1])', 'varchar(20)'),
--change this for multiple columns (depends on the logging)
@colname = @d.value('(/EVENT_INSTANCE/AlterTableActionList/*[1]/Columns/Name)[1]', 'sysname'),
@sqlcommand = @d.value('(/EVENT_INSTANCE/TSQLCommand/CommandText)[1]', 'nvarchar(max)');


if object_id(quotename(@tblschemaname) + '.' + quotename(@tblname)) = object_id('dbo.guineapigtbl')
and @colname is not null
begin
insert into dbo.logtablechanges
(
tableobject_id,
tablename, columnname, theaction, thestatement
)
values
(
object_id(quotename(@tblschemaname) + '.' + quotename(@tblname)),
@tblname, @colname, @action, @sqlcommand
)

end

end
go


--testing
alter table dbo.guineapigtbl add col1 int;
alter table dbo.guineapigtbl add col2 varchar(10);
alter table dbo.guineapigtbl alter column col1 bigint;
alter table dbo.guineapigtbl drop column col1;

--multiple
alter table dbo.guineapigtbl add col3 int, col4 int;

--check log
select *
from logtablechanges

--cleanup
/*
drop table dbo.logtablechanges
drop table dbo.guineapigtbl
drop trigger trig_db_alter_table on database

go
*/

关于sql-server - SQL Server如何监控表结构变化?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59702557/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com