GO
ALTER PROCEDURE [sAlert].[pAlertQueueLogAdd]
	@rId bigint = 0,
	@rMessageDate datetime = null,
	@rQueueMessage nvarchar(max) = '',
	@rEventId int = 0,
	@rAlertModeId tinyint = 0,
	@rOrgId smallint = 0,
	@rCreatedUserId bigint = 0

WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	BEGIN TRY
	BEGIN TRANSACTION	
		IF(@rId = 0)	
		BEGIN
			DECLARE @lNextNumber BIGINT  
			EXECUTE sCommon.pTableRowIdGet @rOrgId, 'sAlert.tAlertQueueLog', 0, 1, 1,@outNextNumber = @lNextNumber output

			INSERT INTO [sAlert].[tAlertQueueLog]
				([AutoId]
				,[MessageDate]
			    ,[QueueMessage]
			    ,[EventId]
			    ,[AlertModeId]
			    ,[OrgId]
			    ,[CreatedUserId]
			    ,[CreatedDateTime])
		   VALUES
				(@lNextNumber
				,@rMessageDate
			    ,@rQueueMessage
			    ,@rEventId
			    ,@rAlertModeId
			    ,@rOrgId
			    ,@rCreatedUserId
			    ,sCommon.fGetDate())

			SELECT @lNextNumber AS Result
		END
		ELSE
		BEGIN
			UPDATE [sAlert].[tAlertQueueLog] SET [QueueMessage] = @rQueueMessage WHERE AutoId = @rId

			SELECT @rId AS Result
		END
	COMMIT TRANSACTION
    END TRY
	
	BEGIN CATCH 
		ROLLBACK TRANSACTION
		SELECT -1 AS Result
	END CATCH	
END
GO