如何在存储过程中创建索引?抱怨
Msg 102,Level 15,State 1,Procedure createIndexModifiedOn,Line 12
'PRIMARY'附近的语法不正确。
但ON [PRIMARY]
是SQL Server本身在创建新索引并选择Script As New Query
时使用的。
如果我删除ON [PRIMARY]
,则会出现此错误
Msg 102,Level 15,State 1,Procedure createIndexModifiedOn,Line 12
')'附近的语法不正确。
以下是程序:
create proc [dbo].createIndexModifiedOn
@table char(256)
as begin
declare @idx char(256)
set @idx = 'idx_' + SUBSTRING(@table, 7, len(@table)-1) + '_modified_on';
IF EXISTS (SELECT * FROM sys.indexes WHERE object_id = OBJECT_ID(@table) AND name = @idx)
DROP INDEX [@idx] ON [@table]
CREATE NONCLUSTERED INDEX [@idx] ON [@table]
(
[modified_on] ASC
) ON [PRIMARY]
go
这最终成为完整的查询:
create proc [dbo].createIndexModifiedOn
@table varchar(256)
as
declare @idx varchar(256);
declare @sql nvarchar(999);
set @idx = 'idx_' + SUBSTRING(@table, 8, len(@table)-8) + '_modified_on';
set @sql = '
IF EXISTS (SELECT * FROM sys.indexes WHERE object_id = OBJECT_ID(''' + @table + ''') AND name = ''' + @idx + ''')
DROP INDEX [' + @idx + '] ON ' + @table + '
CREATE NONCLUSTERED INDEX [' + @idx + '] ON ' + @table + '
(
[modified_on] ASC
) ON [PRIMARY]
';
print @table + ', ' + @idx;
BEGIN TRY
EXEC sp_executesql @sql;
END TRY
BEGIN CATCH
PRINT 'errno: ' + ltrim(str(error_number()))
PRINT 'errmsg: ' + error_message()
END CATCH
GO
EXEC sp_MSforeachtable 'exec createIndexModifiedOn "?"'
答案 0 :(得分:4)
您不能像在CREATE INDEX语句中那样使用变量。为此,您需要生成一个SQL字符串并使用sp_executesql
执行它。
手绘示例:
DECLARE @sql NVARCHAR(1024);
SET @sql = 'CREATE NONCLUSTERED INDEX [' + @idx + '] ON [' + @table + ']
(
[modified_on] ASC
) ON [PRIMARY];';
EXEC sp_executesql @sql;