Solved

Drop and add index usig a variable

Posted on 2014-03-27
2
447 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 33

Accepted Solution

by:
ste5an earned 250 total points
ID: 39960276
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
ID: 39960287
Perfect!
0

Featured Post

What is SQL Server and how does it work?

The purpose of this paper is to provide you background on SQL Server. It’s your self-study guide for learning fundamentals. It includes both the history of SQL and its technical basics. Concepts and definitions will form the solid foundation of your future DBA expertise.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

How to leverage one TLS certificate to encrypt Microsoft SQL traffic and Remote Desktop Services, versus creating multiple tickets for the same server.
International Data Corporation (IDC) prognosticates that before the current the year gets over disbursing on IT framework products to be sent in cloud environs will be $37.1B.
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 to use the SELECT statement in SQL and will be exposed to the many uses the SELECT statement has.

861 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

25 Experts available now in Live!

Get 1:1 Help Now