============== *********** Anonymus Block **************** ===================================
================ ******* 1. Title: Truncate All Tables and Reset Sequences in SQL Using a SQL Loop ******** ===============
DECLARE @tableName NVARCHAR(MAX);
DECLARE @sql NVARCHAR(MAX);

-- Disable foreign key constraints
EXEC sp_MSforeachtable 'ALTER TABLE ? NOCHECK CONSTRAINT ALL';

-- Loop through all tables and delete data instead of truncate
IF EXISTS (SELECT 1 FROM sys.tables)
BEGIN
    DECLARE table_cursor CURSOR FOR 
    SELECT name FROM sys.tables;

    OPEN table_cursor;
    FETCH NEXT FROM table_cursor INTO @tableName;

    WHILE @@FETCH_STATUS = 0
    BEGIN
        SET @sql = 'DELETE FROM ' + QUOTENAME(@tableName) + ';';
        EXEC sp_executesql @sql;

        FETCH NEXT FROM table_cursor INTO @tableName;
    END;

    CLOSE table_cursor;
    DEALLOCATE table_cursor;
END;

-- Reset identity values for tables with an identity column
DECLARE @identityTable NVARCHAR(MAX);
IF EXISTS (SELECT 1 FROM INFORMATION_SCHEMA.TABLES WHERE OBJECTPROPERTY(OBJECT_ID(TABLE_NAME), 'TableHasIdentity') = 1)
BEGIN
    DECLARE identity_cursor CURSOR FOR
    SELECT TABLE_NAME FROM INFORMATION_SCHEMA.TABLES 
    WHERE OBJECTPROPERTY(OBJECT_ID(TABLE_NAME), 'TableHasIdentity') = 1;

    OPEN identity_cursor;
    FETCH NEXT FROM identity_cursor INTO @identityTable;

    WHILE @@FETCH_STATUS = 0
    BEGIN
        SET @sql = 'DBCC CHECKIDENT (' + QUOTENAME(@identityTable) + ', RESEED, 0);';
        EXEC sp_executesql @sql;

        FETCH NEXT FROM identity_cursor INTO @identityTable;
    END;

    CLOSE identity_cursor;
    DEALLOCATE identity_cursor;
END;

-- Enable foreign key constraints
EXEC sp_MSforeachtable 'ALTER TABLE ? CHECK CONSTRAINT ALL';
