I have a situation in my SQL Server 2008.
I need to change a column type, but the indexes are preventing the changes. But because of the database is on several clients, I don't know how many indexes exists involving the column.
Is there any way of getting, programmatically speaking, all indexes that involve the column and drop them, and after the alter table
statement recreate them automatically?
I've heard that disabling them can mess with the table because of the change of type.
I'm changing from tinyint to smallint type.
You can use below script which returns Index Name and Type for specified Table/Column.:
Hope This Helps...
Also try this to know the all the indexes on table with column names:
You can use the built-in tools to do this job. In SQL Server Management Studio, click "Tools" then "Options"
Expand the "SQL Server Object Explorer" set and Within that, click "Scripting".
Scroll down to the "Table And View Options" on the right hand side.
Find the record called "Script Indexes" and set it to "True", then click OK.
When you right click your table in the Object Explorer, you have options to "Script As..." selecting any of these options will now script out the indexes as well as the table itself and its keys. Copy the required scripts, or just run the whole thing depending on your need.
Lets assume basic case (column is not a part of any constraint, not an XML column having XML index over it, etc.), the following can be done:
select (...) from <sys.indexes + other sys schema views> FOR XML ...
DISABLE all indexes on destination table
Then Alter datatype of a column
After that Enable Indexes
Here is some example SQL of dropping and recreating an index safely:
Here is some C# code that pumps this out:
Here's some C# (that can be converted to SQL) to get the index schema:
So, basically, you execute the last piece of code here, iterate through the results (indexes and columns) and call GetCreateIndexScript for each index that is returned. Then you can safely execute each of the statements that are created to drop and recreate the indexes.
This same approach could be used with TSQL, or another language.