Frage

I'm looking for a way to truncate all tables on one schema only. I'm getting the list of all tables on that schema:

*SELECT name, object_id FROM sys.objects WHERE schema_id = (SELECT SCHEMA_ID('seg'))*

but I'm struggling to find a way to TRUNCATE all from the result set.

thanks for any points!

War es hilfreich?

Lösung

Refer to Link OR try this script

DECLARE @SQL NVARCHAR(MAX) = ''

SELECT @SQL = (
    SELECT 'TRUNCATE TABLE [' + s.name + '].[' + o.name + ']' + CHAR(13)
    FROM sys.objects o WITH (NOWAIT)
    JOIN sys.schemas s WITH (NOWAIT) ON o.[schema_id] = s.[schema_id]
    WHERE o.[type] = 'U'
        AND s.name = 'dbo'
    FOR XML PATH(''), TYPE).value('.', 'NVARCHAR(MAX)')

PRINT @SQL

--EXEC sys.sp_executesql @SQL

Andere Tipps

I also found the use of msforeachtable...if anyone would prefer :)

EXEC sp_msforeachtable
       @command1 ='TRUNCATE TABLE ?'
      ,@whereand = ' And Object_id In (SELECT object_id FROM sys.objects WHERE 
                                       schema_id = 6)'
Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top