3

我正在清理 ERP,我需要删除对未使用用户和用户组的引用。有很多外键约束,因此我想确保真正摆脱所有痕迹!

我发现这个整洁的代码花絮可以在我的数据库中找到具有特定列名的所有表,在这种情况下,让我们看看用户组:

select table_name from information_schema.columns
where column_name = 'GROUP_ID'

有了结果,我可以在 40 多个表中搜索我未使用的 ID……但这很乏味。所以我想自动化这个并创建一个循环遍历所有这些表并删除它Unused_GroupGROUP_ID列中找到的行的查询。

在删除任何我想可视化现有数据的内容之前,我开始使用字符串连接构建类似的东西:

declare @group varchar(50) = 'Unused_Group'
declare @table1 varchar(50) = 'TABLE1'
declare @table2 varchar(50) = 'TABLE2'
declare @tableX varchar(50) = 'TABLEX'

select @query1 = 'SELECT ''' + rtrim(@table1)  + ''' as ''Table'', '''
+ rtrim(@group) + ''' = CASE WHEN EXISTS (SELECT GROUP_ID FROM ' + rtrim(@table1)
+ ' WHERE GROUP_ID = ''' + rtrim(@group) + ''') then ''MATCH'' else ''-'' end FROM '
+ rtrim(@table1)

select @query2 = [REPEAT FOR @table2 to @tableX]...

EXEC(@query1 + ' UNION ' + @query2 + ' UNION ' + @queryX)

这给了我结果:

TABLE1  |  Match
TABLE2  |  -
TABLEX  |  Match

这适用于我的目的,我可以在不更改任何其他代码的情况下为任何用户组运行它,当然很容易适应DELETE这些相同的表,但对于我必须在用户和用户之间处理的 75 个左右的表来说是无法管理的团体。

我在动态 SQL 上遇到了这个链接,它的强度和密度足以让我暂时吓跑......但我认为解决方案可能就在某个地方。

我对FOR()JS 和其他语言中的循环非常熟悉,这对于结构良好的数组来说是小菜一碟,但显然它在 SQL 中并不那么简单(我还在学习,但发现了很多关于FOR 和 GOTO 解决方案可用...)。理想情况下,我有一个脚本,可以查询以查找具有特定列名的表,如上所述查询每个表,然后向我吐出一个匹配列表,然后执行第二个类似的脚本来删除行。

谁能帮我指出正确的方向?

4

3 回答 3

1

好的,试试这个,有三个变量;列、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

我对代码进行了注释,以帮助您了解它在做什么;祝你好运!

于 2013-02-11T21:37:15.263 回答
0

你在INFORMATION_SCHEMA对象的正确轨道上。在查询编辑器中执行以下操作,它会为包含具有值的列的表生成SELECT和语句。DELETEGROUP_ID'Unused_Group'

-- build select DML to manually review data that will be deleted
SELECT 'SELECT * FROM [' + TABLE_SCHEMA + '].[' + TABLE_NAME + '] WHERE [GROUP_ID] = ''Unused_Group'';'
FROM INFORMATION_SCHEMA.COLUMNS
WHERE COLUMN_NAME = 'GROUP_ID';

-- build delete DML to remove data
SELECT 'DELETE FROM [' + TABLE_SCHEMA + '].[' + TABLE_NAME + '] WHERE [GROUP_ID] = ''Unused_Group'';'
FROM INFORMATION_SCHEMA.COLUMNS
WHERE COLUMN_NAME = 'GROUP_ID';

由于这似乎是一次性的清理工作,特别是因为您需要在删除数据之前对其进行检查,所以我看不出让这变得更复杂的价值。

于 2013-02-11T20:59:59.653 回答
0

如果可以,请考虑添加参照完整性并强制执行级联删除。在删除数据之前,它不会帮助可视化数据,但有助于控制孤立的行。

于 2013-02-11T21:30:52.913 回答