下面是用于DB表的REBUILD_INDEX的存储过程,它之前执行正常,但是当我现在检查它显示下面的错误时,
Msg 102,Level 15,State 1,Line 3
'活动'附近的语法不正确。Msg 319,Level 15,State 1,Line 3
关键字'与'附近的语法不正确。如果此语句是公用表表达式,xmlnamespaces子句或更改跟踪上下文子句,则前一个语句必须以分号结束
但是没有文字'活动'在存储过程中,并且不使用CTE。无法猜出这个突发问题的原因。谁能给我一个线索?
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
答案 0 :(得分:1)
您应该添加分号并使用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;
我认为解析器错误WITH
公共表格表达式来自WITH
的{{1}}。
无论如何,我会使用Ola Hallengren's SQL Server Index and Statistics Maintenance Scripts而不是重新发明轮子。
答案 1 :(得分:0)
“活动”几乎可以肯定是表名中的一部分,其中包含空格。在ALTER INDEX语句中的@TableName周围添加Quotename(..)。