Created
March 6, 2023 14:58
-
-
Save joanteixi/46c26d479f2d945179cfcc59a104f8b2 to your computer and use it in GitHub Desktop.
T-SQL: Delete All Values in Tables
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
DECLARE @TableName NVARCHAR(128) | |
DECLARE @SQL NVARCHAR(500) | |
DECLARE TableCursor CURSOR FOR | |
SELECT TABLE_NAME | |
FROM INFORMATION_SCHEMA.TABLES | |
WHERE TABLE_TYPE = 'BASE TABLE' | |
OPEN TableCursor | |
FETCH NEXT FROM TableCursor INTO @TableName | |
WHILE @@FETCH_STATUS = 0 | |
BEGIN | |
SET @SQL = 'DELETE FROM [' + @TableName + ']' | |
BEGIN TRY | |
EXECUTE sp_executesql @SQL | |
PRINT 'Truncate table' + @TableName | |
END TRY | |
BEGIN CATCH | |
PRINT 'Failed to truncate table ' + @TableName + '. Error message: ' + ERROR_MESSAGE() | |
END CATCH | |
FETCH NEXT FROM TableCursor INTO @TableName | |
END | |
CLOSE TableCursor | |
DEALLOCATE TableCursor |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment