UPDATE TBDD_MODULES SET DB_VERSION = '2.4.8.6' where NAME = 'Record-Organizer' 
GO 
CREATE PROCEDURE [dbo].[PRPMO_CHECK_DOC_RECORD_LINK] (
	@pRECORD_ID INTEGER,
	@pDOC_ID INTEGER,
	@pREASON_CODE VARCHAR(500),
	@pWHO VARCHAR(50)
	) 
	AS
BEGIN
	IF NOT EXISTS(SELECT GUID FROM TBPMO_DOC_RECORD_LINK WHERE RECORD_ID = @pRECORD_ID AND DOC_ID = @pDOC_ID)
		BEGIN
			INSERT INTO TBPMO_DOC_RECORD_LINK (RECORD_ID,DOC_ID,COMMENT,ADDED_WHO) VALUES 
			(@pRECORD_ID,@pDOC_ID,@pREASON_CODE,@pWHO)
		END
	ELSE
		UPDATE TBPMO_DOC_RECORD_LINK SET CHANGED_WHO = @pWHO WHERE RECORD_ID = @pRECORD_ID AND DOC_ID = @pDOC_ID
END
GO
CREATE TABLE TBPMO_CLIENT_CONNECTION_SWITCH
(
	GUID					INTEGER		IDENTITY(1,1),              	
	[DESCRIPTION]			VARCHAR(100),	
	SQL_CONNECTION			VARCHAR(MAX)	NOT NULL,
	SQL_CONNECTION_PROXY	VARCHAR(MAX)	DEFAULT '',
	WM_ALIAS				VARCHAR(250)	NOT NULL,
	ACTIVE   				BIT				NOT NULL			DEFAULT 1,	
	ADDED_WHO				VARCHAR(50)		NOT NULL			DEFAULT 'DEFAULT',
	ADDED_WHEN				DATETIME 		NOT NULL			DEFAULT GETDATE(),
	CHANGED_WHO				VARCHAR(50),
	CHANGED_WHEN			DATETIME,
	CONSTRAINT		PK_TBPMO_CLIENT_CONNECTION_SWITCH	PRIMARY KEY (GUID)
)
GO
 ------------------------------------------------------------------------------
CREATE TRIGGER TBPMO_CLIENT_CONNECTION_SWITCH_AFT_UPD ON TBPMO_CLIENT_CONNECTION_SWITCH
FOR UPDATE
AS
	UPDATE TBPMO_CLIENT_CONNECTION_SWITCH SET CHANGED_WHEN = GETDATE() FROM INSERTED WHERE TBPMO_CLIENT_CONNECTION_SWITCH.GUID = INSERTED.GUID
GO


CREATE TABLE TBPMO_CLIENT_CONN_SWITCH_USER
(
	GUID			INTEGER			NOT NULL	IDENTITY(1,1),
	CONN_SWITCH_ID	INTEGER			NOT NULL,
	USER_ID			INTEGER			NOT NULL,
	ACTIVE			BIT				NOT NULL	DEFAULT 0,
	ADDED_WHO		VARCHAR(50)		DEFAULT		'DEFAULT',
	ADDED_WHEN		DATETIME 		NOT NULL	DEFAULT GETDATE(),
	CHANGED_WHO		VARCHAR(50),
	CHANGED_WHEN	DATETIME,
	CONSTRAINT		PK_TBPMO_CLIENT_CONN_SWITCH_USER					PRIMARY KEY (GUID),
	CONSTRAINT		UQ_PK_TBPMO_CLIENT_CONN_SWITCH_USER	UNIQUE([USER_ID],CONN_SWITCH_ID),
	CONSTRAINT		FK_TBPMO_CLIENT_CONN_SWITCH_USER_SWITCH_ID	FOREIGN KEY (CONN_SWITCH_ID)  REFERENCES  TBPMO_CLIENT_CONNECTION_SWITCH (GUID),
	CONSTRAINT		FK_TBPMO_CLIENT_CONN_SWITCH_USER_USER_ID			FOREIGN KEY (USER_ID)  REFERENCES  TBDD_USER (GUID)
)
GO
CREATE TRIGGER TBPMO_CLIENT_CONN_SWITCH_USER_AFT_UPD ON TBPMO_CLIENT_CONN_SWITCH_USER
FOR UPDATE
AS
	DECLARE 
		@GUID		INTEGER,
		@OLD_ACTIVE	BIT,
		@NEW_ACTIVE	BIT,
		--@IS_MAIN	BIT,
		@USER_ID	INTEGER
	SELECT 				
		@NEW_ACTIVE = ACTIVE,
		@USER_ID = USER_ID,
		--@IS_MAIN = IS_MAIN,
		@GUID = GUID
	FROM INSERTED
	IF UPDATE(ACTIVE)
		BEGIN
			SELECT 
				@OLD_ACTIVE = DELETED.ACTIVE
			FROM DELETED
			
			IF @NEW_ACTIVE = 1 AND @OLD_ACTIVE = 0
				UPDATE TBPMO_CLIENT_CONN_SWITCH_USER SET ACTIVE = 0 WHERE USER_ID = @USER_ID AND GUID <> @GUID
		END
	
	UPDATE TBPMO_CLIENT_CONN_SWITCH_USER SET CHANGED_WHEN = GETDATE() FROM INSERTED WHERE TBPMO_CLIENT_CONN_SWITCH_USER.GUID = INSERTED.GUID
GO

