/*
DECLARE @TEXT nvarchar(max)
select @TEXT = TEXT from Contents where ContentID Like 17259
select * from vefn_SplitROs(@TEXT)
--\v <START]\v0 11%\v #Link:ReferencedObject:2933 0003000000940000 2[END>\v0

SELECT ContentID, RO.Value, RO.UsageID, 'R' + RO.ROID ROID, RO.RODBID  FROM CONTENTS
CROSS APPLY vefn_SplitROs(TEXT) RO
Where TEXT LIKE '%\v #Link:ReferencedObject:%'

SELECT ContentID --, RO.Value, RO.UsageID, RO.ROID  
FROM CONTENTS
--CROSS APPLY vefn_SplitROs(TEXT) RO
Where TEXT LIKE '%\v #Link:ReferencedObject:%'


SELECT ContentID, RO.Value, RO.UsageID, RO.ROID  FROM CONTENTS
CROSS APPLY vefn_SplitROs(TEXT) RO
Where CONTENTID = 708

*/
CREATE FUNCTION [dbo].[vefn_SplitROs](@text varchar(MAX))
RETURNS @ROValues TABLE
(
	Value varchar(max),
	UsageID int,
	ROID varchar(20),
	RODBID int
)
WITH EXECUTE AS OWNER
AS
BEGIN
DECLARE @START nvarchar(255)
SET @START= '\v <START]\v0 '
DECLARE @MIDDLE nvarchar(255)
SET @MIDDLE = '\v #Link:'
DECLARE @MIDDLERO nvarchar(255)
SET @MIDDLERO = '\v #Link:ReferencedObject:'
DECLARE @END  nvarchar(255)
SET @END = '[END>\'
DECLARE @IndexStart int
SET @IndexStart = CHARINDEX(@START , @text)
DECLARE @IndexEnd int
SET @IndexEnd = CHARINDEX(@END , @text)
WHILE (@IndexStart > 0)
	BEGIN
		DECLARE @PARTS NVARCHAR(MAX)
		DECLARE @PART1 NVARCHAR(MAX)
		DECLARE @PART2 NVARCHAR(MAX)
		DECLARE @PART3 NVARCHAR(MAX)
		SET @IndexStart = @IndexStart + len(@START) + 1
		--PRINT @IndexStart
		--PRINT @IndexEnd
		SET @PARTS = SUBSTRING(@TEXT,@IndexStart,@IndexEnd - @IndexStart)
		--PRINT @PARTS
		DECLARE @IndexMiddle int
		SET @IndexMiddle = CHARINDEX(@Middle , @PARTS)
		SET @PART1 = LEFT(@PARTS,@IndexMiddle-1)
		--PRINT @PART1
		SET @PARTS = SUBSTRING(@PARTS,@IndexMiddle, len(@PARTS))
		IF @PARTS LIKE @MIDDLERO + '%'
		BEGIN
			SET @PARTS = SUBSTRING(@PARTS,len(@MIDDLERO)+1,len(@PARTS))
			DECLARE @IndexSpace int
			SET @IndexSpace = CHARINDEX(' ',@PARTS)
			SET @PART2 = LEFT(@PARTS,@IndexSpace-1)
			--PRINT @PART2
			SET @PARTS = LTRIM(SUBSTRING(@PARTS,@IndexSpace+1,len(@PARTS)))
			SET @IndexSpace = CHARINDEX(' ',@PARTS)
			SET @PART3 = LEFT(@PARTS,@IndexSpace-1)
			--PRINT @PART3
			SET @PARTS = LTRIM(SUBSTRING(@PARTS,@IndexSpace+1,len(@PARTS)))
			--PRINT @PARTS
			Insert INTO @ROValues Values(@PART1, CAST(@PART2 AS INT), @PART3, Cast(@Parts as int))
		END
		SET @TEXT = SUBSTRING(@TEXT,@IndexEnd + LEN(@End), LEN(@TEXT))
		SET @IndexStart = CHARINDEX(@START , @text)
		SET @IndexEnd = CHARINDEX(@END , @text)
	END
RETURN
END