USE [HCITools];
GO

IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Backup_Simple_Databases]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Backup_Simple_Databases]
GO

USE [HCITools]
GO

SET ANSI_NULLS ON;
GO

SET QUOTED_IDENTIFIER ON;
GO

CREATE PROCEDURE [dbo].[Backup_Simple_Databases]
WITH ENCRYPTION
AS 
/*===================================================================================
	Procedure to backup all database in simple recovery mode 

	Backkup only if database update occurs during last 24h 
 
	Creation : 10.01.2023 / RTC
 =====================================================================================*/
IF EXISTS (   SELECT 1
                FROM ActivePos_read.[upd].[DatabaseHistory]
               WHERE VersionDate > DATEADD(hh, -24, GETDATE()))
BEGIN
    
    /* select only databases in simple recovery mode */
    DECLARE @database_list VARCHAR(4000);
    SELECT @database_list = '';

    SELECT @database_list = @database_list + name + ',' --,name, * 
      FROM master.sys.databases
     WHERE recovery_model_desc = 'SIMPLE'
       AND name NOT IN ( 'tempdb' );

    SET @database_list = SUBSTRING(@database_list, 1, (LEN(@database_list) - 1));

    DECLARE @password VARCHAR(255);

    SET @password
        = HCITools.dbo.fn_Decrypt(
              0x01000000C2811DD6D0339FF2EFE6AE1181B3469D18798020836E3E0A1E4BC96D548B4FCDFFB77F264E1A4F42AD91F785284A6F5D4F3E533B0355E88F91A61E7E671472D3F580FC36CCF0AE48858099190C1B7E3A1A2A292A3E8809B40EAB6EAECF3C0FF6871CAF54A3928615C21830602BCB12F1F973E4B4B1F34A613B342C397372596025DB62CB426319AE916D0DC5CCAED8A62675D7602D592A92);

    /* BACKUP TARGET DATABASES */
    EXEC HCITools.[dba].[Commvault_Operation] @in_type = 'Backup',
                                     @in_username = 'CLI_SQL_Backup',
                                     @in_password = @password,
                                     @in_subclientName = 'OnDemand',
                                     @in_databasetobackup = @database_list,
                                     @in_callerApp = 'DBA backup';
END;