Do statistics referencing a column prevent that column from being dropped?

前端 未结 2 1601
小蘑菇
小蘑菇 2021-02-19 08:11

I\'m trying a very simple drop column statement:

alter table MyTable drop column MyColumn

and receiving several errors along the l

2条回答
  •  盖世英雄少女心
    2021-02-19 09:08

    The code proposed in JNK answer does not work, but the idea is good. If you want to delete all user created statistics this my tested solution :

    DECLARE @sql NVARCHAR(MAX)
    
    DECLARE statCursor CURSOR FOR 
    SELECT 
        'DROP STATISTICS ' + QUOTENAME(SCHEMA_NAME(t.schema_id)) 
                            + '.' + QUOTENAME(t.name) 
                            + '.' + QUOTENAME(st.name) AS sql
    FROM
        sys.stats AS st 
        INNER JOIN sys.tables AS t
            ON st.object_id = t.object_id
    WHERE
        st.user_created = 1
    ORDER BY 1;
    
    OPEN statCursor;
    
    FETCH NEXT FROM statCursor INTO @sql
    WHILE @@FETCH_STATUS = 0  
    BEGIN  
        PRINT @sql
        EXEC sp_executesql @sql
        FETCH NEXT FROM statCursor INTO @sql
    END  
    CLOSE statCursor  
    DEALLOCATE statCursor
    

提交回复
热议问题