问题
I have a column "StoreNumber" in my "Project" table which I want to change to be "NOT NULL". I recently sanitized all of the old data so that there are no null entries. However, when I execute the following statement it fails due to multiple dependencies to various views, indexes, and statistics
ALTER TABLE [Project]
ALTER COLUMN StoreNumber VARCHAR(9) NOT NULL
GO
What is the fastest way to drop all of these views/indexes/statistics then run the alter statement, and then recreate all of the views/indexes/statistics again? I know that I could copy out all of the drop and create statements one by one but I would prefer to generate the script in a single query.
On a side note, why does SQL Server care if I'm making the column more restrictive? The data does not contain nulls and I'm not altering the data type or the size of the columns. How would this type of change ever break a dependent view, index, or statistics? I'm sure there is sound reasoning that I'm not seeing but I would like an example.
回答1:
Just thinking; will it work if you set a default value first? (dind't check the sintax myself)
ALTER TABLE Project
ADD CONSTRAINT col_sn_def
DEFAULT '' FOR StoreNumber;
GO
回答2:
The following will drop multiple indexes. Note that the final statement does not include the comma.
DROP INDEX [index1_1] ON [schema].[table1],
[index1_2] ON [schema].[table1],
[index2_1] ON [schema].[table2],
[index3_1] ON [schema].[table3],
...n,
[lastIndexToDrop] ON [schema].[tableName]
Drop View looks like this. Note the semicolon to terminate the statement.
DROP VIEW [schema].[view1], [schema].[view2];
I am only concerned with Indexes in my application at this time. To quickly recreate the indexes, I am reading a .sql file into code and executing it in an ExecuteNonQuery call. If I had views to consider, I would follow the same method of reading from a file into a command to execute with ExecuteNonQuery.
https://msdn.microsoft.com/en-us/library/ms173492.aspx
https://msdn.microsoft.com/en-us/library/ms176118.aspx
来源:https://stackoverflow.com/questions/18281686/quickly-dropping-and-re-creating-multiple-indexes-views-statistics-when-alteri