How to exclude tables from sp_msforeachtable

前端 未结 3 1948
星月不相逢
星月不相逢 2021-01-01 11:23

I know that sp_msforeachtable allows to perform queries on all tables.

I have 100 tables and I want to perform the same query on 97 tables.

I\'

相关标签:
3条回答
  • 2021-01-01 11:47
    EXEC sp_MSforeachtable 'IF OBJECT_ID(''?'') NOT IN (
                                                        ISNULL(OBJECT_ID(''[dbo].[T1]''),0),
                                                        ISNULL(OBJECT_ID(''[dbo].[T2]''),0)
                                                       )
                            DELETE FROM ?'
    
    0 讨论(0)
  • 2021-01-01 11:54

    Simplest syntax I came across to include or exclude schemas and tables:

    exec sp_MSforeachtable 'print ''?''', 
    @whereand='and Schema_Id=Schema_id(''Value'') and o.Name like ''%Value%'''
    
    0 讨论(0)
  • 2021-01-01 12:02

    sp_MSforeachtable is undocumented procedure, but according by that example: http://avinashkt.blogspot.ru/2008/05/useful-operations-with-spmsforeachtable.html you could provide additional second parameter @whereand to limit list of tables.


    The query that this gets appended to is the following.

    SELECT   '[' + REPLACE(schema_name(syso.schema_id), N']', N']]') + ']' 
           + '.' 
           + '[' + REPLACE(object_name(o.id), N']', N']]') + ']'
    FROM   dbo.sysobjects o
           JOIN sys.all_objects syso
             ON o.id = syso.object_id
    WHERE  OBJECTPROPERTY(o.id, N'IsUserTable') = 1
           AND o.category & ltrim(str(CONVERT(INT, 0x0002))) = 0 
    

    So example syntax would be

       EXEC sp_MSforeachtable @command1 = N'PRINT ''?'' ', 
                              @whereand = 'AND o.id NOT IN (
                                                         ISNULL(OBJECT_ID(''[dbo].[T1]''),0), 
                                                         ISNULL(OBJECT_ID(''[dbo].[T2]''),0)  
                                                           )'
    
    0 讨论(0)
提交回复
热议问题