Solved

Drop and add index usig a variable

Posted on 2014-03-27
2
440 Views
Last Modified: 2014-03-27
Hello,

Trying to drop index on a table. But doesn't seem to work

DECLARE @indexName VARCHAR(50);
SELECT @indexName =  i.name
FROM sysobjects o, sysindexes i
WHERE  (o.id = i.id and o.name = 'MyTable') AND i.name like ('%NonClustered%')

DROP INDEX [@indexName] ON [dbo].[MyTable]

ALTER TABLE [dbo].[Link]
ALTER COLUMN [myColumn] [nvarchar](120)

CREATE INDEX [@indexName] ON [dbo].[MyTable] (myColumn)

"Cannot drop the index 'dbo.MyTable.@indexName', because it does not exist or you do not have permission."

I am able to get the correct index name but unable to execute drop index command with a variable.
0
Comment
Question by:sansoftura
2 Comments
 
LVL 32

Accepted Solution

by:
Stefan Hoffmann earned 250 total points
Comment Utility
You cannot use a variable in the DROP statement directly. Use dynamic SQL instead. E.g.

DECLARE @indexName VARCHAR(50);
SELECT @indexName =  i.name
FROM sysobjects o, sysindexes i
WHERE  (o.id = i.id and o.name = 'MyTable') AND i.name like ('%NonClustered%');

DECLARE @Sql NVARCHAR(MAX) = N'DROP INDEX ' + QUOTENAME(@indexName) +' ON [dbo].[MyTable]';
EXECUTE (@Sql);

ALTER TABLE [dbo].[Link]
ALTER COLUMN [myColumn] [nvarchar](120);

SET @Sql = N'CREATE INDEX ' + QUOTENAME(@indexName) +'  ON [dbo].[MyTable] (myColumn);';
EXECUTE (@Sql);

Open in new window

0
 
LVL 6

Author Closing Comment

by:sansoftura
Comment Utility
Perfect!
0

Featured Post

How to run any project with ease

Manage projects of all sizes how you want. Great for personal to-do lists, project milestones, team priorities and launch plans.
- Combine task lists, docs, spreadsheets, and chat in one
- View and edit from mobile/offline
- Cut down on emails

Join & Write a Comment

Everyone has problem when going to load data into Data warehouse (EDW). They all need to confirm that data quality is good but they don't no how to proceed. Microsoft has provided new task within SSIS 2008 called "Data Profiler Task". It solve th…
For both online and offline retail, the cross-channel business is the most recent pattern in the B2C trade space.
Using examples as well as descriptions, and references to Books Online, show the documentation available for datatypes, explain the available data types and show how data can be passed into and out of variables.
Viewers will learn how the fundamental information of how to create a table.

772 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

10 Experts available now in Live!

Get 1:1 Help Now