0

Below is the stored procedure used for REBUILD_INDEX of DB tables, It was executing fine before but when I checked now it is showing below error,

Msg 102, Level 15, State 1, Line 3
Incorrect syntax near 'Activity'.

Msg 319, Level 15, State 1, Line 3
Incorrect syntax near the keyword 'with'. If this statement is a common table expression, an xmlnamespaces clause or a change tracking context clause, the previous statement must be terminated with a semicolon

But there's no text 'Activity' in the stored procedure, and no CTE is used. Not able to guess the reason for this sudden issue. Can anyone give me a clue on this?

USE [DBName]
GO

/****** Object:  StoredProcedure [dbo].[REBUILD_INDEX]
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

ALTER PROCEDURE [dbo].[REBUILD_INDEX]
AS
BEGIN

DECLARE @TableName VARCHAR(255)
DECLARE @sql NVARCHAR(500)
DECLARE @fillfactor INT
SET @fillfactor = 80
DECLARE TableCursor CURSOR FOR
SELECT OBJECT_SCHEMA_NAME([object_id])+'.'+name AS TableName
FROM sys.tables
OPEN TableCursor
FETCH NEXT FROM TableCursor INTO @TableName
WHILE @@FETCH_STATUS = 0
BEGIN
SET @sql = 'ALTER INDEX ALL ON ' + @TableName + ' REBUILD WITH (FILLFACTOR = ' + CONVERT(VARCHAR(3),@fillfactor) + ')'
EXEC (@sql)
FETCH NEXT FROM TableCursor INTO @TableName
END
CLOSE TableCursor
DEALLOCATE TableCursor

END
marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
Sathiya Kumar V M
  • 507
  • 12
  • 34

2 Answers2

1

You should add semicolons and use QUOTENAME:

ALTER PROCEDURE [dbo].[REBUILD_INDEX]
AS
BEGIN

DECLARE @TableName VARCHAR(255);
DECLARE @sql NVARCHAR(500);
DECLARE @fillfactor INT;
SET @fillfactor = 80;
DECLARE TableCursor CURSOR FOR
SELECT OBJECT_SCHEMA_NAME([object_id])+'.'+QUOTENAME(name) AS TableName
FROM sys.tables;
OPEN TableCursor;
FETCH NEXT FROM TableCursor INTO @TableName;
WHILE @@FETCH_STATUS = 0
BEGIN
SET @sql = 'ALTER INDEX ALL ON ' + @TableName 
   + ' REBUILD WITH (FILLFACTOR = ' + CONVERT(VARCHAR(3),@fillfactor) + ');';

PRINT @sql; -- debug only
EXEC (@sql);

FETCH NEXT FROM TableCursor INTO @TableName;
END;
CLOSE TableCursor;
DEALLOCATE TableCursor;

END;

I bet parser mistakes WITH Common Table Expression with WITH from ALTER INDEX.


Anyway I would use Ola Hallengren's SQL Server Index and Statistics Maintenance Scripts instead of reinventing the wheel.

Lukasz Szozda
  • 162,964
  • 23
  • 234
  • 275
0

The "Activity" is almost certainly part of a Table Name with a space in it. Add Quotename(..) around the @TableName in the ALTER INDEX statement.

Sean Devoy
  • 66
  • 5