CREATE PROC [dbo].[sp_SetLabelValues]
(
	@srcSurfaceId INT --= 3098
)
AS

DECLARE @srcItemId INT
		,@surfaceListToUpdate VARCHAR(500) = ''

DECLARE labelCursor CURSOR FOR
	
	SELECT	I.recId
	FROM	pal_SurfaceItem I
	WHERE	I.surfaceId = @srcSurfaceId		
			AND I.isActive = 1

	OPEN labelCursor      
		FETCH NEXT FROM labelCursor INTO @srcItemId      
    
	WHILE @@FETCH_STATUS=0 
	BEGIN 		
		DECLARE @surfaceListTemp VARCHAR(250)			
		EXEC sp_ReSetItemLabelValues @srcItemId,@srcSurfaceId,@surfaceListTemp OUTPUT	 
		SELECT	@surfaceListToUpdate = dbo.[SplitAndRemoveDuplicates](',', @surfaceListToUpdate+','+CAST(@surfaceListTemp AS VARCHAR(250)))
		FETCH NEXT FROM labelCursor INTO @srcItemId         
	END   

CLOSE labelCursor      
DEALLOCATE labelCursor  

DECLARE @pos INT = 0
DECLARE @len INT = 0
DECLARE @value varchar(50)

WHILE CHARINDEX(',', @surfaceListToUpdate, @pos+1)>0
BEGIN
    set @len = CHARINDEX(',', @surfaceListToUpdate, @pos+1) - @pos
    set @value = SUBSTRING(@surfaceListToUpdate, @pos, @len)

	EXEC sp_CreateSurfaceQueryTable @value,0,219,0

    set @pos = CHARINDEX(',', @surfaceListToUpdate, @pos+@len) +1
END
