飞仙 发表于 2007-7-5 10:23:08

修改用户定义的数据类型

--SQLSERVER的自定义类型比较好用吧,但是,一旦引用该数据类型后,想修改数据类型,就是一大头疼的事了,本存储过程就是专门对付它的。

--sp_rebuildallview 见本BLOG中的其它页面
create procedure sp_rechangfieldtype(@typename varchar(50), @newtype varchar(50))
as
begin

declare @typeid int
declare @tablename varchar(50)
declare @column varchar(50)

declare @sqlstr varchar(200)
declare @defaultid int


select @typeid = xusertype
from systypes
where name = @typename and xusertype > 256
AND (is_member('db_owner') = 1 OR is_member('db_ddladmin') = 1 OR is_member(user_name(uid))=1)

declare mycursor cursor for
select o.name, c.name, c.cdefault
from syscolumns c, systypes t, sysusers u, sysobjects o
where c.xusertype = @typeid
and t.xusertype = @typeid
and o.uid = u.uid
and c.id = o.id
and o.type = 'u'

open mycursor
fetch next from mycursor into @tablename, @column, @defaultid
while @@fetch_status = 0
begin
if @defaultid <> 0
begin
set @sqlstr = &#39;alter table &#39; + @tablename + &#39; drop &#39; + object_name(@defaultid)
exec(@sqlstr)

set @sqlstr = &#39;alter table &#39; + @tablename + &#39; alter column &#39; + @column + &#39; &#39; + @newtype
exec(@sqlstr)

--set @sqlstr = &#39;alter table &#39; + @tablename + &#39; add contraint &#39; + @tablename + &#39;df&#39;+@column + &#39; default 0&#39;

end
else
begin
set @sqlstr = &#39;alter table &#39; + @tablename + &#39; alter column &#39; + @column + &#39; &#39; + @newtype

print @sqlstr
exec(@sqlstr)
end
--if @@error <> 0
-- continue
fetch next from mycursor into @tablename, @column, @defaultid
end
--如果没有约束,则可以直接删除。如果有约束。先处理约束。

close mycursor
deallocate mycursor

end

GO

create procedure SP_CHANGEFIELD(@OLDTYPENAME VARCHAR(50), @NEWDTYPE VARCHAR(50))
as
begin

exec(&#39;sp_addtype U_LOCALTYPE, &#39;&#39;&#39; + @newdtype + &#39;&#39;&#39;&#39;)

exec SP_rechangfieldtype @OLDTYPENAME, &#39;U_LOCALTYPE&#39;

EXEC sp_rebuildallview

EXEC(&#39;sp_droptype &#39; + @OLDTYPENAME)

EXEC(&#39;sp_addtype &#39; + @OLDTYPENAME + &#39;, &#39;&#39;&#39; + @newdtype + &#39;&#39;&#39;&#39;)

exec SP_rechangfieldtype &#39;U_LOCALTYPE&#39;, @OLDTYPENAME

EXEC sp_rebuildallview

EXEC sp_droptype &#39;U_LOCALTYPE&#39;

end
GO


--以下是示例。将U_HELLO的长度改为 30

SP_ADDTYPE U_HELLO, &#39;VARCHAR(10)&#39;

GO
CREATE TABLE TESTTYPE(NAME U_HELLO)
GO

SP_CHANGEFIELD &#39;U_HELLO&#39;, &#39;VARCHAR(30)&#39;

jackwei057 发表于 2010-5-13 17:46:54

楼主可以讲讲怎么使用吗

heang567 发表于 2023-12-28 10:19:39

来学习一下来学习一下
页: [1]
查看完整版本: 修改用户定义的数据类型