How to exclude tables from sp_msforeachtable

user194076 picture user194076 · Oct 21, 2011 · Viewed 15k times · Source

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?

Answer

Martin Smith picture Martin Smith · Oct 21, 2011
EXEC sp_MSforeachtable 'IF OBJECT_ID(''?'') NOT IN (
                                                    ISNULL(OBJECT_ID(''[dbo].[T1]''),0),
                                                    ISNULL(OBJECT_ID(''[dbo].[T2]''),0)
                                                   )
                        DELETE FROM ?'