BEGIN TRAN 
	DECLARE @viewid uniqueidentifier, @usercategoryid int;

	CREATE TABLE #userCat
	(
	   [Id] int, [ViewId] uniqueidentifier, [Name] varchar(max)
	);

	DECLARE uniqueViewsCursor CURSOR -- Declare cursor

	LOCAL STATIC

	FOR
	SELECT DISTINCT [ViewId]
	FROM [dbo].[PL_View];

	OPEN uniqueViewsCursor -- open the cursor

	FETCH NEXT FROM uniqueViewsCursor
	INTO @viewid
	WHILE @@FETCH_STATUS = 0
	BEGIN
		TRUNCATE TABLE #userCat;
		INSERT INTO #userCat
			SELECT [Id], [ViewId], [Name]
			  FROM [dbo].[PL_UserCategories]
			  WHERE Name='Uncategorized' AND ViewId=@viewid;

		IF NOT EXISTS(select * from #userCat)
		BEGIN
		    insert into [dbo].[PL_UserCategories]
			 ([Name],
			   [ViewId])
			values ('Uncategorized', @viewid)

			 SET @usercategoryid = SCOPE_IDENTITY();
		END
		ELSE
		BEGIN
			select @usercategoryid=[Id] from #userCat;
		END

		UPDATE [dbo].[PL_LinkOrder]
		SET [UserCategoryId]=@usercategoryid
		WHERE [UserCategoryId] IS NULL AND [ViewId]=@viewid

		FETCH NEXT FROM uniqueViewsCursor
		INTO @viewid
	END
	CLOSE uniqueViewsCursor -- close the cursor

	DEALLOCATE uniqueViewsCursor -- Deallocate the cursor

	DROP TABLE #userCat;

	
	IF EXISTS (SELECT *  FROM sys.indexes WHERE name='IX_FK_PL_UserCategoryPL_LinkOrder' 
		AND object_id = OBJECT_ID('[dbo].[PL_LinkOrder]'))
	BEGIN
		DROP INDEX [IX_FK_PL_UserCategoryPL_LinkOrder] ON [dbo].[PL_LinkOrder];

		ALTER TABLE [dbo].[PL_LinkOrder] 
		ALTER COLUMN [UserCategoryId] INTEGER NOT NULL;

		-- Creating non-clustered index for FOREIGN KEY 'FK_PL_UserCategoryPL_LinkOrder'
		CREATE INDEX [IX_FK_PL_UserCategoryPL_LinkOrder]
		ON [dbo].[PL_LinkOrder]
			([UserCategoryId]);
	END
	ELSE
	BEGIN
		ALTER TABLE [dbo].[PL_LinkOrder] 
		ALTER COLUMN [UserCategoryId] INTEGER NOT NULL;
	END
	GO

	IF @@ERROR <> 0 
	BEGIN 
	  ROLLBACK TRAN
	END
COMMIT TRAN
GO

