讨论: 如何修改自定义数据类型的类型和长度

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.05--*/

/*--调用示例

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'

--3.修改表,使用新增的自定义变量
declare @s varchar(8000)
declare tb cursor local
for select 'alter table ['+object_name(a.id)+'] alter column ['
+a.name+'] '+@typename
from syscolumns a join systypes b on a.xusertype=b.xusertype
where b.name=@bktypename and objectproperty(a.id,N'IsUserTable')=1
open tb
fetch next from tb into @s
while @@fetch_status=0
begin
exec(@s)
fetch next from tb into @s
end
close tb
deallocate tb

--刷新视图
declare hCForEach cursor global for
select '[' + REPLACE(user_name(uid), N']', N']]')+'].['
+ REPLACE(object_name(id), N']', N']]')+ ']'
from dbo.sysobjects
where xtype='V' and status>=0
exec sp_MSforeach_worker 'sp_refreshview ''?'''

--刷新存储过程,自定义函数,触发器
declare hCForEach cursor global for
select '[' + 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 'sp_recompile ''?'''

if @deloldtype=1
exec sp_droptype @bktypename
commit tran
set nocount off
go

Published At
Categories with 数据库类
comments powered by Disqus