How do I create an index inside a stored procedure? It complains
Msg 102, Level 15, State 1, Procedure createIndexModifiedOn, Line 12
Incorrect syntax near 'PRIMARY'.
But ON [PRIMARY]
is what SQL Server itself uses if you create a new index and select Script As New Query
.
If I remove ON [PRIMARY]
then it gives this error
Msg 102, Level 15, State 1, Procedure createIndexModifiedOn, Line 12
Incorrect syntax near ')'.
Here is the procedure:
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
This ended up being the full query:
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 "?"'
You can't use variables in the CREATE INDEX statement as you have. To do this, you will need to generate a SQL string and execute it with sp_executesql
.
Freehand example:
DECLARE @sql NVARCHAR(1024);
SET @sql = 'CREATE NONCLUSTERED INDEX [' + @idx + '] ON [' + @table + ']
(
[modified_on] ASC
) ON [PRIMARY];';
EXEC sp_executesql @sql;
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.