Altering user-defined table types in SQL Server

前端 未结 7 1514
心在旅途
心在旅途 2020-12-13 12:06

How can I alter a user-defined table type in SQL Server ?

7条回答
  •  情书的邮戳
    2020-12-13 12:34

    This is kind of a hack, but does seem to work. Below are the steps and an example of modifying a table type. One note is the sp_refreshsqlmodule will fail if the change you made to the table type is a breaking change to that object, typically a procedure.

    1. Use sp_rename to rename the table type, I typically just add z to the beginning of the name.
    2. Create a new table type with the original name and any modification you need to make to the table type.
    3. Step through each dependency and run sp_refreshsqlmodule on it.
    4. Drop the renamed table type.

    EXEC sys.sp_rename 'dbo.MyTableType', 'zMyTableType';
    GO
    CREATE TYPE dbo.MyTableType AS TABLE(
        Id INT NOT NULL,
        Name VARCHAR(255) NOT NULL
    );
    GO
    DECLARE @Name NVARCHAR(776);
    
    DECLARE REF_CURSOR CURSOR FOR
    SELECT referencing_schema_name + '.' + referencing_entity_name
    FROM sys.dm_sql_referencing_entities('dbo.MyTableType', 'TYPE');
    
    OPEN REF_CURSOR;
    
    FETCH NEXT FROM REF_CURSOR INTO @Name;
    WHILE (@@FETCH_STATUS = 0)
    BEGIN
        EXEC sys.sp_refreshsqlmodule @name = @Name;
        FETCH NEXT FROM REF_CURSOR INTO @Name;
    END;
    
    CLOSE REF_CURSOR;
    DEALLOCATE REF_CURSOR;
    GO
    DROP TYPE dbo.zMyTableType;
    GO
    

    WARNING:

    This can be destructive to your database, so you'll want to test this on a development environment first.

提交回复
热议问题