
DECLARE @id uniqueidentifier, @alias varchar(255), @sql nvarchar(max)
SET @sql = ''
DECLARE db_cursor CURSOR FOR  
select PeriodSectionID, PeriodAlias 
from T_PERIOD_SECTION
order by Priority

OPEN db_cursor   
FETCH NEXT FROM db_cursor INTO @id, @alias   

WHILE @@FETCH_STATUS = 0   
BEGIN   
       IF(LEN(@sql)>0)
	   BEGIN
			SET @sql = @sql + ' UNION ALL ' 
	   END
       set @sql =   @sql + ' SELECT CAST([MonthValuesID] AS VARCHAR(36)) + ''' +  cast(@id as varchar(36)) +  ''' AS MonthValueID, MonthValuesID as MonthValues, CAST(''' + cast(@id as varchar(36)) + ''' as uniqueidentifier) AS PeriodSection, ' + @alias + ' AS Value FROM [dbo].[T_MONTH_VALUES]'
	   FETCH NEXT FROM db_cursor INTO @id, @alias  
END   

CLOSE db_cursor   
DEALLOCATE db_cursor
--print @sql

DECLARE @view nvarchar(max)
EXEC sp_executesql @view
SET @view = N'CREATE VIEW [dbo].[V_MONTH_VALUE] AS ' + @sql 
exec sp_executesql @view

--SET @view =+ N'CREATE UNIQUE CLUSTERED INDEX PK_V_MONTH_VALUE_MonthValueID ON [dbo].[V_MONTH_VALUE] (MonthValueID);'
--exec sp_executesql @view