--sqlserver的自定义类型比较好用吧,但是,一旦引用该数据类型后,想修改数据类型,就是一大头疼的事了,本存储过程就是专门对付它的。 --sp_rebuildallview 见本blog中的其它页面 create procedure sp_rechangfieldtype(@typename varchar(50), @newtype v
--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 = 'alter table ' + @tablename + ' drop ' + object_name(@defaultid)
exec(@sqlstr)
set @sqlstr = 'alter table ' + @tablename + ' alter column ' + @column + ' ' + @newtype
exec(@sqlstr)
-- set @sqlstr = 'alter table ' + @tablename + ' add contraint ' + @tablename + 'df'+@column + ' default 0'
end
else
begin
set @sqlstr = 'alter table ' + @tablename + ' alter column ' + @column + ' ' + @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('sp_addtype u_localtype, ''' + @newdtype + '''')
exec sp_rechangfieldtype @oldtypename, 'u_localtype'
exec sp_rebuildallview
exec('sp_droptype ' + @oldtypename)
exec('sp_addtype ' + @oldtypename + ', ''' + @newdtype + '''')
exec sp_rechangfieldtype 'u_localtype', @oldtypename
exec sp_rebuildallview
exec sp_droptype 'u_localtype'
end
go
--以下是示例。将u_hello的长度改为 30
sp_addtype u_hello, 'varchar(10)'
go
create table testtype(name u_hello)
go
sp_changefield 'u_hello', 'varchar(30)'