if exists (select * from dbo.sysobjects where id = object_id(N\'[dbo].[p_changeusertype]\') and OBJECTPROPERTY(id, N\'IsProcedure\') = 1)
drop procedure [dbo].[p_changeusertype]
GO
/*--存储过程功能说明
修改当前库中定义的用户定义数据类型的长度及精度
并自动修改所有的表/视图/存储过程/触发器/自定义函数中的对应定义
由于数据库的复杂性,建议修改前先备份
--作者:邹建 2004.06--*/
/*--调用示例
exec p_changeusertype \'test\',\'nvarchar(20)\'
--*/
create proc p_changeusertype
@typename sysname, --要修改的用户定义数据类型名
@newdef sysname, --新的用户定义数据类型的定义
@allownull bit=1, --新的用户定义数据类型是否允许NULL,为1表示允许,为0表示不允许
@deloldtype bit=1 --是否在处理完成后删除旧的用户定义数据类型,默认为删除
as
declare @bktypename nvarchar(36)
if not exists(select 1 from systypes where name=@typename)
begin
print \'------------------------------------------------\'
print \' 要修改的用户定义数据类型不存在\'
print \'------------------------------------------------\'
return
end
set nocount on
set @bktypename=cast(newid() as varchar(36))
print \'------------------------------------------------\'
print \' 原来的用户定义数据类型将被改名为: \'+@bktypename
print \'------------------------------------------------\'
set xact_abort on
begin tran
--1.修改旧用户定义数据类型的名称
exec sp_rename @typename,@bktypename,\'USERDATATYPE\'
--2.新增用户定义数据类型(按新的定义)
if @allownull=1
exec sp_addtype @typename,@newdef,N\'null\'
else
exec sp_addtype @typename,@newdef,N\'not null\'
declare hCForEach cursor global for
--修改表结构定义的处理语句
select \'alter table [\'+replace(user_name(uid), N\']\',N\']]\')+\'].[\'
+replace(object_name(id),N\']\',N\']]\')+\'] alter column [\'
+replace(a.name,N\']\',N\']]\')+\'] \'+@typename
from syscolumns a join systypes b on a.xusertype=b.xusertype
where b.name=@bktypename and objectproperty(a.id,N\'isusertable\')=1
union all --刷新视图的语句
select \'exec sp_refreshview \'\'[\'+replace(user_name(uid), N\']\',N\']]\')+\'].[\'
+replace(object_name(id),N\']\',N\']]\')+\']\'\'\'
from dbo.sysobjects
where xtype=\'v\' and status>=0
union all --刷新存储过程,自定义函数,触发器的语句
select \'exec sp_recompile \'\'[\' + replace(user_name(uid), N\']\', N\']]\')+\'].[\'
+ replace(object_name(id), N\']\', N\']]\')+ \']\'\'\'
from dbo.sysobjects
where xtype in(\'tr\',\'fn\',\'if\',\'tf\',\'p\') and status>=0
exec sp_msforeach_worker \'?\'
if @deloldtype=1
exec sp_droptype @bktypename
commit tran
set nocount off
go