UPDATE TBDD_MODULES SET DB_VERSION = '2.5.0.0' where NAME = 'Record-Organizer' 
GO 
CREATE TABLE [dbo].[TBPMO_DOC_IN_WORK_HISTORY](
	[GUID] [bigint] IDENTITY(1,1) NOT NULL,
	[DOCID] [bigint] NOT NULL,
	[COMMENT] [varchar](500) NULL,
	[IN_WORK_WHO] [varchar](50) NOT NULL,
	[IN_WORK_WHEN] [datetime] NOT NULL,
	[FREE_WHO] [varchar](50) NULL,
	[FREE_WHEN] [datetime] NULL,
 CONSTRAINT [PK_TBPMO_DOC_IN_WORK_HISTORY] PRIMARY KEY CLUSTERED 
(
	[GUID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]

GO
ALTER TABLE [dbo].[TBPMO_DOC_IN_WORK_HISTORY] ADD  DEFAULT ('DEFAULT') FOR [IN_WORK_WHO]
GO
ALTER TABLE [dbo].[TBPMO_DOC_IN_WORK_HISTORY] ADD  DEFAULT (getdate()) FOR [IN_WORK_WHEN]
GO

ALTER TRIGGER [dbo].[TBPMO_DOCRESULT_LIST_AFT_UPD] ON [dbo].[TBPMO_DOCRESULT_LIST]
FOR UPDATE
AS
	IF UPDATE (IN_WORK)
		BEGIN
			DECLARE @IN_WORK BIT, 
			@IN_WORK_USER VARCHAR(50),
			@IN_WORK_COMMENT VARCHAR(500),
			@DocID		BIGINT

			SELECT 
				@DocID = DocID,
				@IN_WORK = IN_WORK,
				@IN_WORK_USER = IN_WORK_USER,
				@IN_WORK_COMMENT = IN_WORK_COMMENT
			FROM INSERTED
			IF @IN_WORK = 1
				INSERT INTO TBPMO_DOC_IN_WORK_HISTORY (DOCID,COMMENT,IN_WORK_WHO) VALUES (@DocID,@IN_WORK_COMMENT,@IN_WORK_USER)
			ELSE
				BEGIN
					UPDATE TBPMO_DOC_IN_WORK_HISTORY SET FREE_WHO = @IN_WORK_USER, FREE_WHEN = GETDATE() WHERE DOCID = @DocID AND FREE_WHEN IS NULL
					UPDATE TBPMO_DOCRESULT_LIST SET IN_WORK_COMMENT = NULL FROM INSERTED WHERE TBPMO_DOCRESULT_LIST.[DocID] = INSERTED.[DocID]
				END

		END
	UPDATE TBPMO_DOCRESULT_LIST SET CHANGED_WHEN = GETDATE() FROM INSERTED WHERE TBPMO_DOCRESULT_LIST.[DocID] = INSERTED.[DocID]


