DECLARE @PrimaryKeyName SYSNAME
DECLARE @SQL_QUERY NVARCHAR(MAX);

	IF EXISTS(SELECT 1 FROM sys.columns 
			  WHERE Name = N'Id'
			  AND Object_ID = Object_ID(N'dbo.PL_LinkOrder'))
	BEGIN
	   /*Delete existing duplicate rows*/
		SET @SQL_QUERY = N'DELETE FROM PL_LinkOrder
		WHERE Id NOT IN(SELECT MIN(Id)
		FROM PL_LinkOrder
		GROUP BY PrincipalID, ViewID, UserCategoryId);'
		EXEC sp_executesql @SQL_QUERY;
	END

	/*Drop existing primary key*/
	SELECT @PrimaryKeyName = CONSTRAINT_NAME FROM INFORMATION_SCHEMA.TABLE_CONSTRAINTS 
	WHERE  TABLE_NAME = 'PL_LinkOrder' AND CONSTRAINT_CATALOG = DB_NAME() AND TABLE_CATALOG = DB_NAME() AND CONSTRAINT_TYPE = 'PRIMARY KEY'

	IF @PrimaryKeyName IS NOT NULL
	BEGIN
		SET @SQL_QUERY = N'ALTER TABLE PL_LinkOrder DROP CONSTRAINT ' + @PrimaryKeyName
		EXEC sp_executesql @SQL_QUERY;
	END

	IF EXISTS(SELECT 1 FROM sys.columns 
			  WHERE Name = N'Id'
			  AND Object_ID = Object_ID(N'dbo.PL_LinkOrder'))
	BEGIN
		/*Drop existing primary key field Id*/
		SET @SQL_QUERY = N'ALTER TABLE PL_LinkOrder DROP COLUMN  Id'
		EXEC sp_executesql @SQL_QUERY;
	END

	

	/*Add new primary key*/
	SET @SQL_QUERY = N'ALTER TABLE PL_LinkOrder ADD CONSTRAINT '+ ISNULL(@PrimaryKeyName, 'PK_PL_LinkOrder') + N' PRIMARY KEY CLUSTERED (PrincipalID, ViewID, UserCategoryId)'
	EXEC sp_executesql @SQL_QUERY;

