/*
21.01.2025, TSC
*/
BEGIN TRANSACTION 
SET XACT_ABORT ON;
SET NOCOUNT ON;

DECLARE @query NVARCHAR(MAX);
DECLARE @tplCheckUser NVARCHAR(MAX);
DECLARE @tplUser NVARCHAR(MAX);
DECLARE @login VARCHAR(255);
DECLARE @userExists INT = -10;

SET @login='centralinfra\L-CI-AP-SQL-D-HCI-Diverse_R'
--SET @login='centralinfra\L-CI-AP-SQL-D-HCI-Diverse_RW'


SET @tplCheckUser='
USE @db@;
SELECT @userExists = 99
FROM [sys].[database_principals] dp
WHERE [dp].[name] = ''@login@''

';

SET @tplUser='
USE @db@;
DROP USER [@login@];
';

DECLARE @csrDbName VARCHAR(255);
DECLARE csrAllDbs CURSOR FAST_FORWARD READ_ONLY FOR 
    SELECT [d].[name]
    FROM sys.databases d
    WHERE [d].[database_id] >4 
    AND d.[is_read_only] = 0            --ignore read only dbs
    AND d.[source_database_id] IS NULL  --ignore snapshot
    AND d.[state] = 0                   --db is online

OPEN csrAllDbs
                
    FETCH NEXT FROM csrAllDbs INTO @csrDbName
                
    WHILE @@FETCH_STATUS = 0
    BEGIN
        --Create the user in the db
        SET @query = REPLACE(
                        REPLACE(@tplCheckUser, '@db@', @csrDbName)
                        ,'@login@'
                        , @login
                    );
        EXEC [sys].[sp_executesql]
            @query
            ,N'@userExists INT OUTPUT'
            , @userExists OUTPUT
            ;
        -- -10 is the default (not set) value. if a user did exists, the previous dynamic sql would have assigned the value 99
        IF @userExists = 99
        BEGIN
            --drop user
            SELECT @query = REPLACE(
                                REPLACE(@tplUser, '@db@', @csrDbName)
                                ,'@login@'
                                ,@login
                            );
            EXECUTE [sys].[sp_executesql]
                @query
                ,N''
                ;
            --PRINT @query;
        END
        PRINT CONVERT(VARCHAR(20), CURRENT_TIMESTAMP, 114)+' - dropped user "Diverse" in db '+@csrDbName;

        FETCH NEXT FROM csrAllDbs INTO @csrDbName
    END
                
CLOSE csrAllDbs
DEALLOCATE csrAllDbs


--ROLLBACK TRANSACTION 
COMMIT TRANSACTION 
