Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to exclude tables from sp_msforeachtable

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'm using this query: EXEC sp_MSForEachTable "DELETE FROM ?"

Is it possible to exclude certain tables?

like image 529
user194076 Avatar asked Oct 21 '11 17:10

user194076


3 Answers

EXEC sp_MSforeachtable 'IF OBJECT_ID(''?'') NOT IN (
                                                    ISNULL(OBJECT_ID(''[dbo].[T1]''),0),
                                                    ISNULL(OBJECT_ID(''[dbo].[T2]''),0)
                                                   )
                        DELETE FROM ?'
like image 51
Martin Smith Avatar answered Oct 18 '22 15:10

Martin Smith


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%'''
like image 11
Alex Hinton Avatar answered Oct 18 '22 15:10

Alex Hinton


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)  
                                                       )'
like image 6
Hubbitus Avatar answered Oct 18 '22 16:10

Hubbitus