好的,试试这个,有三个变量;列、colValue 和预览。Column 应该是您正在检查相等性的列 (Group_ID),colValue 是您要查找的值 (Unused_Group),preview 应该是 1 以查看您将删除的内容,0 以删除它。
Declare @column Nvarchar(256),
@colValue Nvarchar(256),
@preview Bit
Set @column = 'Group_ID'
Set @colValue = 'Unused_Group'
Set @preview = 1 -- 1 = preview; 0 = delete
If Object_ID('tempdb..#tables') Is Not Null Drop Table #tables
Create Table #tables (tID Int, SchemaName Nvarchar(256), TableName Nvarchar(256))
-- Get all the tables with a column named [GROUP_ID]
Insert #tables
Select Row_Number() Over (Order By s.name, so.name), s.name, so.name
From sysobjects so
Join sys.schemas s
On so.uid = s.schema_id
Join syscolumns sc
On so.id = sc.id
Where so.xtype = 'u'
And sc.name = @column
Select *
From #tables
Declare @SQL Nvarchar(Max),
@schema Nvarchar(256),
@table Nvarchar(256),
@iter Int = 1
-- As long as there are tables to look at keep looping
While Exists (Select 1
From #tables)
Begin
-- Get the next table record to look at
Select @schema = SchemaName,
@table = TableName
From #tables
Where tID = @iter
-- If the table we're going to look at has dependencies on tables we have not
-- yet looked at move it to the end of the line and look at it after we look
-- at it's dependent tables (Handle foreign keys)
If Exists (Select 1
From sysobjects o
Join sys.schemas s1
On o.uid = s1.schema_id
Join sysforeignkeys fk
On o.id = fk.rkeyid
Join sysobjects o2
On fk.fkeyid = o2.id
Join sys.schemas s2
On o2.uid = s2.schema_id
Join #tables t
On o2.name = t.TableName Collate Database_Default
And s2.name = t.SchemaName Collate Database_Default
Where o.name = @table
And s1.name = @schema)
Begin
-- Move the table to the end of the list to retry later
Update t
Set tID = (Select Max(tID) From #tables) + 1
From #tables t
Where tableName = @table
And schemaName = @schema
-- Move on to the next table to look at
Set @iter = @iter + 1
End
Else
Begin
-- Delete the records we don't want anymore
Set @Sql = Case
When @preview = 1
Then 'Select * ' -- If preview is 1 select from table
Else 'Delete t ' -- If preview is not 1 the delete from table
End +
'From [' + @schema + '].[' + @table + '] t
Where ' + @column + ' = ''' + @colValue + ''''
Exec sp_executeSQL @SQL;
-- After we've done the work remove the table from our list
Delete t
From #tables t
Where tableName = @table
And schemaName = @schema
-- Move on to the next table to look at
Set @iter = @iter + 1
End
End
将其转换为存储过程只需将顶部的变量声明更改为 sproc 创建,这样您就可以摆脱...
Declare @column Nvarchar(256),
@colValue Nvarchar(256),
@preview Bit
Set @column = 'Group_ID'
Set @colValue = 'Unused_Group'
Set @preview = 1 -- 1 = preview; 0 = delete
...
并将其替换为...
Create Proc DeleteStuffFromManyTables (@column Nvarchar(256), @colValue Nvarchar(256), @preview Bit = 1)
As
...
你会用...来称呼它
Exec DeleteStuffFromManyTable 'Group_ID', 'Unused_Group', 1
我对代码进行了注释,以帮助您了解它在做什么;祝你好运!