How to exclude tables from sp_msforeachtable

丶灬走出姿态 提交于 2019-12-18 18:40:00

问题


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?


回答1:


EXEC sp_MSforeachtable 'IF OBJECT_ID(''?'') NOT IN (
                                                    ISNULL(OBJECT_ID(''[dbo].[T1]''),0),
                                                    ISNULL(OBJECT_ID(''[dbo].[T2]''),0)
                                                   )
                        DELETE FROM ?'



回答2:


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%'''



回答3:


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)  
                                                       )'


来源:https://stackoverflow.com/questions/7852979/how-to-exclude-tables-from-sp-msforeachtable

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!