I'm trying to partitioning one table on my database, this particular table has more than 4 million records and I'm using the code bellow to create the partitionin by the datetime column IPE_DTL. Creating the partitioning dynamicaly. But when I try to create the index (just like the end of script ) its returning to me the following error:
Could not find any index named 'IDX_cad_ipe_PartitionBy_DTL' for table 'cad_ipe'.
What am I doing wrong?
CREATE PARTITION FUNCTION pf_PartitionByMonthYear(DATE)
AS RANGE RIGHT FOR VALUES ();
CREATE PARTITION SCHEME ps_PartitionByMonthYear
AS PARTITION pf_PartitionByMonthYear ALL TO ([PRIMARY]);
CREATE TABLE #UniqueMonths (MonthYearValue INT PRIMARY KEY);
INSERT INTO #UniqueMonths (MonthYearValue)
SELECT DISTINCT CONVERT(INT, FORMAT(IPE_DTL, 'yyyyMM'))
FROM cad_ipe
ORDER BY CONVERT(INT, FORMAT(IPE_DTL, 'yyyyMM'))
DECLARE @monthyear_value INT;
DECLARE @SqlCmd NVARCHAR(MAX);
DECLARE @formatted_date_value NVARCHAR(8);
DECLARE monthyear_cursor CURSOR FOR
SELECT MonthYearValue FROM #UniqueMonths;
OPEN monthyear_cursor;
FETCH NEXT FROM monthyear_cursor INTO @monthyear_value;
WHILE @@FETCH_STATUS = 0
BEGIN
SET @formatted_date_value = CAST(@monthyear_value AS NVARCHAR(6));
SET @SqlCmd = 'ALTER DATABASE Teste ADD FILEGROUP FG_cad_ipe_' + @formatted_date_value + ';';
EXEC sp_executesql @SqlCmd;
SET @SqlCmd = '
ALTER DATABASE Teste
ADD FILE (
NAME = N''cad_ipe_data_' + @formatted_date_value + ''',
FILENAME = N''B:\MSSQL\DATA\cad_ipe_data_' + @formatted_date_value + '.ndf'',
SIZE = 5MB,
MAXSIZE = UNLIMITED,
FILEGROWTH = 5MB
) TO FILEGROUP FG_cad_ipe_' + @formatted_date_value + ';
';
EXEC sp_executesql @SqlCmd;
SET @SqlCmd = 'ALTER PARTITION SCHEME ps_PartitionByMonthYear
NEXT USED FG_cad_ipe_' + @formatted_date_value + ';
ALTER PARTITION FUNCTION pf_PartitionByMonthYear()
SPLIT RANGE (''' + @formatted_date_value + '01' + ''')';
EXEC sp_executesql @SqlCmd;
FETCH NEXT FROM monthyear_cursor INTO @monthyear_value;
END;
CLOSE monthyear_cursor;
DEALLOCATE monthyear_cursor;
DROP TABLE #UniqueMonths;
CREATE CLUSTERED INDEX [IDX_cad_ipe_PartitionBy_DTL]
ON [cad_ipe] (IPE_DTL)
WITH (DROP_EXISTING = ON)
ON ps_PartitionByMonthYear(IPE_DTL);
I fixed the code to use the partition adding the following:
SET @SqlCmd = 'ALTER PARTITION SCHEME ps_PartitionByMonthYear
NEXT USED FG_cad_ipe_' + @formatted_date_value + ';
ALTER PARTITION FUNCTION pf_PartitionByMonthYear()
SPLIT RANGE (''' + @formatted_date_value + '01' + ''')';
EXEC sp_executesql @SqlCmd;
but I'm still geting the error to create the custered index.