Go Premium for a chance to win a PS4. Enter to Win

x
?
Solved

Drop and add index usig a variable

Posted on 2014-03-27
2
Medium Priority
?
512 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 36

Accepted Solution

by:
ste5an earned 1000 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

In the first part of this tutorial we will cover the prerequisites for installing SQL Server vNext on Linux.
What if you have to shut down the entire Citrix infrastructure for hardware maintenance, software upgrades or "the unknown"? I developed this plan for "the unknown" and hope that it helps you as well. This article explains how to properly shut down …
Familiarize people with the process of retrieving data from SQL Server using an Access pass-thru query. Microsoft Access is a very powerful client/server development tool. One of the ways that you can retrieve data from a SQL Server is by using a pa…
Viewers will learn how to use the INSERT statement to insert data into their tables. It will also introduce the NULL statement, to show them what happens when no value is giving for any given column.

972 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