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 "?"'
yes, we can create an Index within the Stored Procedure.
SQL Server CREATE INDEX statement In this syntax: First, specify the name of the index after the CREATE NONCLUSTERED INDEX clause. Note that the NONCLUSTERED keyword is optional. Second, specify the table name on which you want to create the index and a list of columns of that table as the index key columns.
The INDEX is used to create and retrieve data from the database very quickly. An Index can be created by using a single or group of columns in a table. When the index is created, it is assigned a ROWID for each row before it sorts out the data.
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;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With