UPDATE TBDD_MODULES SET DB_VERSION = '3.4' where NAME = 'Process-Manager';
GO

SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
ALTER PROCEDURE [dbo].[PRTF_PROFILE_FILES_WORK] @pDocID BIGINT,@pProfilID INTEGER,@pUserID INTEGER, @pMode VARCHAR(100)
AS
BEGIN
	-- Race Condition verhindern mit MERGE
    MERGE TBTF_PROFILE_FILES_WORK AS target
    USING (SELECT @pProfilID AS ProfileID, @pDocID AS DocID) AS source
    ON (target.ProfileID = source.ProfileID AND target.DocID = source.DocID)
    WHEN NOT MATCHED THEN
        INSERT (ProfileID, DocID, Action_UserID, Action_When, InWork, Worked)
        VALUES (@pProfilID, @pDocID, @pUserID, GETDATE(), 0, 0);

	IF @pMode = 'FreeFile'
		BEGIN
			PRINT 'FreeFile ...'
			UPDATE TBTF_PROFILE_FILES_WORK SET InWork = 0, Action_When = NULL, Action_UserID = @pUserID
				WHERE DocID = @pDocID AND ProfileID = @pProfilID AND InWork = 1;
		END
	ELSE IF @pMode = 'InWork'
		UPDATE TBTF_PROFILE_FILES_WORK SET InWork = 1, Action_When = GETDATE(), Action_UserID = @pUserID
			WHERE DocID = @pDocID AND ProfileID = @pProfilID AND InWork = 0;
	ELSE IF @pMode = 'Worked'
		UPDATE TBTF_PROFILE_FILES_WORK SET InWork = 0,Worked = 1, Action_When = GETDATE(), Action_UserID = @pUserID
			WHERE DocID = @pDocID AND ProfileID = @pProfilID AND Worked = 0;
END
