I'm trying to execute the following dynamic query code:
declare @sql nvarchar(max)
set @sql = 'DECLARE @DatePartitionFunction nvarchar(max) = N''CREATE PARTITION FUNCTION DatePartitionFunction (datetime)
AS RANGE RIGHT FOR VALUES ('';
DECLARE @incremental_date nvarchar(150);
select @incremental_date = '+CONVERT(VARCHAR(24),GETDATE(),112)+'
declare @counter int = 0;
WHILE @counter < 3
BEGIN
SET @DatePartitionFunction += '''' + CONVERT(VARCHAR(24),DATEADD(DD, @counter, @incremental_date),112) + '''' + N'', '';
SET @counter += 1;
END
SET @DatePartitionFunction += '''' + CONVERT(VARCHAR(24),DATEADD(DD, @counter, @incremental_date),112) + '''' + N'');'';
print (@DatePartitionFunction)
end;'
exec (@sql);
However, it returns an error stating incorrect syntax.
When I execute the same code outside the dynamic query context, it returns output. Stated below is the same code outside the dynamic query context
DECLARE @DatePartitionFunction nvarchar(max) = N'CREATE PARTITION FUNCTION DatePartitionFunction (datetime)
AS RANGE RIGHT FOR VALUES (';
DECLARE @incremental_date nvarchar(150);
select @incremental_date = CONVERT(VARCHAR(24),GETDATE(),112)
declare @counter int = 0;
WHILE @counter < 3
BEGIN
SET @DatePartitionFunction += '''' + CONVERT(VARCHAR(24),DATEADD(DD, @counter, @incremental_date),112) + '''' + N', ';
SET @counter += 1;
END
SET @DatePartitionFunction += '''' + CONVERT(VARCHAR(24),DATEADD(DD, @counter, @incremental_date),112) + '''' + N');';
print (@DatePartitionFunction);
It produces the desired output text as imparted below:
CREATE PARTITION FUNCTION DatePartitionFunction (datetime)
AS RANGE RIGHT FOR VALUES ('20150923', '20150924', '20150925', '20150926');
This is what i want the console to output in case of the aforementioned dynamic query, however I'm being met with errors. Help!
