CREATE TABLE TBPMO_CONTROL_IMAGE
(
	GUID			INTEGER			NOT NULL	IDENTITY(1,1),
	CONTROL_ID		INTEGER			NOT NULL,
	RECORD_ID		INTEGER			NOT NULL,
	IMG				VARBINARY(max)	NOT NULL,
	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_CONTROL_IMAGE				PRIMARY KEY (GUID),
	CONSTRAINT		UQ_CONTROLID_RECORDID UNIQUE (CONTROL_ID, RECORD_ID),
	CONSTRAINT		FK_TBPMO_CONTROL_IMAGE_CONTROL_ID	FOREIGN KEY (CONTROL_ID) REFERENCES TBPMO_CONTROL (GUID),
	CONSTRAINT		FK_TBPMO_CONTROL_IMAGE_RECORD_ID	FOREIGN KEY (RECORD_ID) REFERENCES  TBPMO_RECORD (GUID),
			
)
GO

CREATE TRIGGER TBPMO_CONTROL_IMAGE_AFT_UPD ON TBPMO_CONTROL_IMAGE
FOR UPDATE
AS
BEGIN 
	DECLARE @RECORD_ID	INTEGER, @CHANGED_WHO VARCHAR(50)
	SELECT 
		@RECORD_ID = RECORD_ID,
		@CHANGED_WHO = CHANGED_WHO
	FROM INSERTED
	
	UPDATE TBPMO_CONTROL_IMAGE 
	SET CHANGED_WHEN = GETDATE() FROM INSERTED 
	WHERE TBPMO_CONTROL_IMAGE.GUID = INSERTED.GUID

	UPDATE TBPMO_RECORD SET
		CHANGED_WHO = @CHANGED_WHO
	WHERE TBPMO_RECORD.GUID = @RECORD_ID
END