-- T3-MultiSourceSummary
DECLARE @JustForDebug TINYINT = 0;

-- SETUP VARIABLES
DECLARE @Number INT = (SELECT COUNT(id) + 1  FROM [diunabi-morska].[dbo].[Layers]);
DECLARE @CurrentTimestamp NVARCHAR(14) = FORMAT(GETDATE(), 'yyyyMMddHHmm');
DECLARE @Name NVARCHAR(50) = CONCAT(
    'L', @Number, '-D-D3_B2B-', @CurrentTimestamp
);
DECLARE @LayerId UNIQUEIDENTIFIER = NEWID();

SELECT @Name AS Name, @Query AS Query;

IF @JustForDebug = 1
BEGIN
    SELECT 'Just for debug' AS Logger;
    RETURN;
END;

INSERT INTO [diunabi-morska].[dbo].[Layers]
([Id], [Number], [Name], [CreatedAt], [ModifiedAt], [IsDeleted], [CreatedById], [ModifiedById], [Type])
VALUES (@LayerId, @Number, @Name, GETDATE(), GETDATE(), 0, '117be4f0-b5d1-41a1-a962-39dc30cce368', '117be4f0-b5d1-41a1-a962-39dc30cce368', 3);

DECLARE @Array TABLE (
    Code NVARCHAR(50),
    Desc1 NVARCHAR(50)
);

INSERT INTO @Array (Code, Desc1)
VALUES 
    ('3089','402-2-001'),
    ('3084','402-2-002'),
    ('3045','402-2-003'),
    ('????','402-2-004', 'GODLEWSKA JOANNA'),
    ('????','402-2-005', 'HABOWSKA URSZULA'),
    ('3010','JANCZEWSKA DOROTA'),
    ('????','402-2-007', 'PROMEDA SP ZOO'),
    ('3091','402-2-008'),
    ('3090','402-2-009'),
    ('3092','402-2-010'),
    ('????','402-2-011'),
    ('3093','402-2-012'),
    ('????','402-2-013', 'ŚWINIARSKA BEATA'),
    ('3094','402-2-014'),
    ('????','402-2-015', 'WIERZBOWSKA');

-- Loop through the array and insert into the target table
DECLARE @Code NVARCHAR(50);
DECLARE @Desc1 NVARCHAR(50);

DECLARE CursorArray CURSOR FOR
SELECT Code, Desc1 FROM @Array;

OPEN CursorArray;

FETCH NEXT FROM CursorArray INTO @Code, @Desc1;

WHILE @@FETCH_STATUS = 0
BEGIN
    INSERT INTO [diunabi-morska].[dbo].[Records]
    ([Id], [Code], [Desc1], [CreatedAt], [ModifiedAt], [CreatedById], [ModifiedById], [IsDeleted], [LayerId])
    VALUES (NEWID(), @Code, @Desc1, GETDATE(), GETDATE(), '117be4f0-b5d1-41a1-a962-39dc30cce368', '117be4f0-b5d1-41a1-a962-39dc30cce368', 0, @LayerId);

    FETCH NEXT FROM CursorArray INTO @Code, @Desc1;
END;

CLOSE CursorArray;
DEALLOCATE CursorArray;
