CREATE FUNCTION [dbo].[FN_SPLIT_STRING]
(    
      @Input NVARCHAR(MAX),
      @Character CHAR(1)
)
RETURNS @Output TABLE (
      Item NVARCHAR(1000)
)
AS
BEGIN
      DECLARE @StartIndex INT, @EndIndex INT
 
      SET @StartIndex = 1
      IF SUBSTRING(@Input, LEN(@Input) - 1, LEN(@Input)) <> @Character
      BEGIN
            SET @Input = @Input + @Character
      END
 
      WHILE CHARINDEX(@Character, @Input) > 0
      BEGIN
            SET @EndIndex = CHARINDEX(@Character, @Input)
           
            INSERT INTO @Output(Item)
            SELECT SUBSTRING(@Input, @StartIndex, @EndIndex - 1)
           
            SET @Input = SUBSTRING(@Input, @EndIndex + 1, LEN(@Input))
      END
 
      RETURN
END

GO

--FUNKTION ZUR AKTUALISIERUNG der DATEN


BEGIN
	DECLARE
		@GUID			INTEGER,
		@CONTROL_ID		INTEGER,
		@RECORD_ID		INTEGER,
		@VALUE			VARCHAR(MAX),
		@NEW_VALUE		VARCHAR(MAX),
		@INDEX			INTEGER,
		@ADDED_WHO		VARCHAR(50)
								
	DECLARE c_Values CURSOR FOR 
		SELECT GUID,CONTROL_ID,RECORD_ID,VALUE,ADDED_WHO FROM TBPMO_CONTROL_VALUE WHERE VALUE LIKE '%;%' AND CONTROL_ID NOT IN (SELECT GUID FROM TBPMO_CONTROL WHERE CONTROL_TYPE_ID = 2) ORDER BY RECORD_ID,CONTROL_ID
  	OPEN c_Values 
    	FETCH NEXT FROM c_Values INTO @GUID,@CONTROL_ID,@RECORD_ID,@VALUE,@ADDED_WHO
    	WHILE @@FETCH_STATUS = 0
		BEGIN
			SET @INDEX = 0
			--#####
			DECLARE c_NEWVALUES CURSOR FOR 
				SELECT Item FROM dbo.FN_SPLIT_STRING(@VALUE, ';')	
  			OPEN c_NEWVALUES 
    			FETCH NEXT FROM c_NEWVALUES INTO @NEW_VALUE
    			WHILE @@FETCH_STATUS = 0
				BEGIN
					SET @NEW_VALUE = LTRIM(@NEW_VALUE)
					IF @INDEX = 0
						UPDATE TBPMO_CONTROL_VALUE SET VALUE = @NEW_VALUE WHERE GUID = @GUID
					ELSE
						INSERT INTO TBPMO_CONTROL_VALUE (CONTROL_ID,RECORD_ID,VALUE,ADDED_WHO) VALUES
						(@CONTROL_ID,@RECORD_ID,@NEW_VALUE,@ADDED_WHO)
					PRINT CONVERT(VARCHAR(5),@CONTROL_ID) + '#' + CONVERT(VARCHAR(5),@INDEX) + '-' + @NEW_VALUE
					SET @INDEX = @INDEX + 1       	
					FETCH NEXT FROM c_NEWVALUES INTO @NEW_VALUE
				END
			CLOSE c_NEWVALUES
			DEALLOCATE c_NEWVALUES
			--#####
			FETCH NEXT FROM c_Values INTO @GUID,@CONTROL_ID,@RECORD_ID,@VALUE,@ADDED_WHO
		END
	CLOSE c_Values
	DEALLOCATE c_Values
  END