
CREATE OR ALTER TRIGGER MIG_TEXTS_TRIGGER  
ON MIG_TEXTS 
INSTEAD OF INSERT 
AS  
BEGIN  
	DECLARE @TEXT_ID INT, @TEXT NVARCHAR(MAX), @TABLE_NAME VARCHAR(8), @FIELD_NAME VARCHAR(4), @ZZ_ID INT, @TMP_TEXT_ID INT, @CUR_TT_TEXT_ID INT
	
	SELECT @CUR_TT_TEXT_ID = IsNull(VALUE,0) FROM MIG_SETTINGS WHERE NAME = 'TT_TEXT_MAX_ID'
	
	SELECT @TEXT_ID = IsNull(MAX(TEXT_ID),@CUR_TT_TEXT_ID)  -- Later we should replace "0" in "ISNULL" with initial seed value from MIG_SETTINGS
	FROM MIG_TEXTS   

	--SELECT @TMP_TEXT_ID=COUNT(*) FROM INSERTED 
	--PRINT(@TMP_TEXT_ID)

	DECLARE TEXTS_INSERT CURSOR 
	LOCAL  FORWARD_ONLY  FOR  
	SELECT TABLE_NAME, FIELD_NAME, ZZ_ID, TEXT_ID, [TEXT] FROM INSERTED   
	OPEN TEXTS_INSERT  
	FETCH NEXT FROM TEXTS_INSERT INTO  @TABLE_NAME, @FIELD_NAME, @ZZ_ID, @TMP_TEXT_ID, @TEXT 
	WHILE @@FETCH_STATUS = 0  
	BEGIN  
	 
		DECLARE @CUR_TEXT_ID INT 
		IF(LEN(@TEXT) > 0)
			BEGIN
				SET @TEXT_ID = @TEXT_ID + 1 
				SET @CUR_TEXT_ID = @TEXT_ID
			END
		ELSE
			SET @CUR_TEXT_ID = 0

		INSERT INTO MIG_TEXTS (TABLE_NAME, FIELD_NAME, ZZ_ID, TEXT_ID, [TEXT])
		VALUES(@TABLE_NAME, @FIELD_NAME, @ZZ_ID, @CUR_TEXT_ID, @TEXT)

		FETCH NEXT FROM TEXTS_INSERT INTO  @TABLE_NAME, @FIELD_NAME, @ZZ_ID, @TMP_TEXT_ID, @TEXT 
	END  
	CLOSE TEXTS_INSERT  
	DEALLOCATE TEXTS_INSERT  

END
