CREATE PROCEDURE [dbo].[STIAddPrescription]
    @PrescriptionId BIGINT,
    @UserId SMALLINT,
    @PrecriptionType SMALLINT = 0
AS
DECLARE @Id UNIQUEIDENTIFIER;
DECLARE @Status SMALLINT = -1;

SELECT @Status = [Status],
       @Id = Id
FROM dbo.STITransaction
WHERE InvoiceId = @PrescriptionId;

IF @Status = -1
BEGIN
    INSERT INTO dbo.STITransaction
    (
        InvoiceId,
        Status,
        Type,
        CreatedBy
    )
    VALUES
    (@PrescriptionId, 0, @PrecriptionType, @UserId);
    SELECT 0 ResultCode;
END;
ELSE IF @Status IN ( 2, 3 )
BEGIN
    UPDATE dbo.STITransaction
    SET Status = 0,
        ResultMessage = NULL,
        ErrorCode = NULL,
        JsonResult = NULL,
        ResultId = NULL,
        CreatedOn = GETDATE(),
        CreatedBy = @UserId
    WHERE Id = @Id;
    SELECT 1 ResultCode;
END;
ELSE IF @Status = 1
    SELECT 2 ResultCode;
ELSE IF @Status = 4
    SELECT 3 ResultCode;
ELSE IF @Status = 0
    SELECT 4 ResultCode;
