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?
EXEC sp_MSforeachtable 'IF OBJECT_ID(''?'') NOT IN (
ISNULL(OBJECT_ID(''[dbo].[T1]''),0),
ISNULL(OBJECT_ID(''[dbo].[T2]''),0)
)
DELETE FROM ?'
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%'''
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)
)'
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With