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 + '''')