How do I add an index to every table using sp_MSforeachtable? It keeps giving errors.
EXEC sp_MSforeachtable @precommand = 'declare @idx as char;',
@command1 = '
set @idx = ''idx_'' + ? + ''_modified_on'';
print @idx;
IF EXISTS (SELECT * FROM sys.indexes WHERE object_id = OBJECT_ID(N''[dbo].[?]'') AND name = N''@idx'')
DROP INDEX [@idx] ON [dbo].[?]
CREATE NONCLUSTERED INDEX [@idx] ON [dbo].[?]
(
[modified_on] ASC
) ON [PRIMARY]
'
One such error:
Msg 137, Level 15, State 1, Line 2
Must declare the scalar variable "@idx".
I try to place the declare inside the command, but then get this error:
Msg 4104, Level 16, State 1, Line 3
The multi-part identifier "dbo.DIAG_contractAuditHistory" could not be bound.
Here is an updated attempt to fix syntax errors, with test SQL as well, but it still gave strange errors. I ended up solving the problem with a stored procedure and calling the stored procedure for each table.
EXEC sp_MSforeachtable @command1 = '
declare @idx as varchar(256);
set @idx = ''idx_'' + SUBSTRING(''?'', 8, len(''?'')-8) + ''_modified_on'';
print @idx;
IF EXISTS (SELECT * FROM sys.indexes WHERE object_id = OBJECT_ID(N''?'') AND name = @idx )
DROP INDEX [@idx] ON ?
IF EXISTS (select * from sys.columns where object_id = OBJECT_ID(N''?'') and name = ''modified_on'')
CREATE NONCLUSTERED INDEX [@idx] ON ?
(
[modified_on] ASC
) ON [PRIMARY]
'
declare @cat as char;
set @cat='dog';
print @cat;
EXEC sp_MSforeachtable 'print ''idx_'' + SUBSTRING(''?'', 8, len(''?'')-8) + ''_modified_on'';'
EXEC sp_MSforeachtable 'print ''?'''
print substring('[dbo].[merchantNotes]', 8, (len('[dbo].[merchantNotes]')-9))
select * from sys.columns where object_id = OBJECT_ID(N'[dbo].[banks]') and name = 'modified_on'
SELECT * FROM sys.indexes WHERE object_id = OBJECT_ID(N'contractPaymentHistory') AND name = 'idx_contractPaymentHistory_modified_on'
This would work for about two dozen tables, then it gives strange errors like
Msg 1934, Level 16, State 1, Line 9 CREATE INDEX failed because the following SET options have incorrect settings: 'QUOTED_IDENTIFIER'. Verify that SET options are correct for use with indexed views and/or indexes on computed columns and/or filtered indexes and/or query notifications and/or XML data type methods and/or spatial index operations.
So I ended up using a different strategy and created a stored procedure to create the indices: How do I create an index inside a stored procedure?