IF EXISTS ( SELECT * 
            FROM   sysobjects 
            WHERE  id = object_id(N'dbo.CP_ImageExport') 
                   and OBJECTPROPERTY(id, N'IsProcedure') = 1 )
BEGIN
    DROP PROCEDURE dbo.CP_ImageExport
END
GO


CREATE PROCEDURE dbo.CP_ImageExport (
	@pNombreArchivo   NVARCHAR(1000),
	@pCarpetaDestino  NVARCHAR(1000),
	@pImageData		  VARBINARY (max)
	)
AS
BEGIN
--- Variables Locales ---------
   DECLARE @Ruta_Foto NVARCHAR (2000);
   DECLARE @Obj INT


		SET NOCOUNT ON

		SET @Ruta_Foto = CONCAT (
				 @pCarpetaDestino
				 ,'\'
				 , @pNombreArchivo 
				 )+'.jpg';


		BEGIN TRY
			EXEC sp_OACreate 'ADODB.Stream' ,@Obj OUTPUT;
			EXEC sp_OASetProperty @Obj ,'Type',1;
			EXEC sp_OAMethod @Obj,'Open';
			EXEC sp_OAMethod @Obj,'Write', NULL, @pImageData;
			EXEC sp_OAMethod @Obj,'SaveToFile', NULL, @Ruta_Foto, 2;
			EXEC sp_OAMethod @Obj,'Close';
			EXEC sp_OADestroy @Obj;
		END TRY
    
		BEGIN CATCH
		EXEC sp_OADestroy @Obj;
		END CATCH
 
		SET NOCOUNT OFF


END
GO



/*

EXEC dbo.CP_ImageExport 'E:\Usuarios\clever-a.barraza.CLEVERSOFT\Desktop\export-prueba'

*/



