create procedure sp_rechangfieldtype(@typename varchar(50), @newtype varchar(50))asbegindeclare @typeid intdeclare @tablename varchar(50)declare @column varchar(50)declare @sqlstr varchar(200)declare @defaultid intselect @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 forselect o.name, c.name, c.cdefaultfrom syscolumns c, systypes t, sysusers u, sysobjects owhere c.xusertype = @typeid and t.xusertype = @typeid and o.uid = u.uid and c.id = o.id and o.type = 'u'open mycursorfetch next from mycursor into @tablename, @column, @defaultidwhile @@fetch_status = 0begin 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, @defaultidend--如果没有约束,则可以直接删除。如果有约束。先处理约束。close mycursordeallocate mycursorendGOcreate procedure SP_CHANGEFIELD(@OLDTYPENAME VARCHAR(50), @NEWDTYPE VARCHAR(50))asbegin 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'endGO--以下是示例。将U_HELLO的长度改为 30SP_ADDTYPE U_HELLO, 'VARCHAR(10)'GOCREATE TABLE TESTTYPE(NAME U_HELLO)GOSP_CHANGEFIELD 'U_HELLO', 'VARCHAR(30)'
create procedure sp_rebuildallviewasbegindeclare @mytext varchar(8000)declare @id intdeclare mycursor cursor forselect c.text from dbo.syscomments c, dbo.sysobjects o where o.id = c.id and o.type = 'v'order by c.number, c.colidopen mycursorfetch next from mycursor into @mytextwhile @@fetch_status =0begin set @id = patindex('%create%', @mytext) set @mytext = stuff(@mytext, @id, 6, 'Alter') print @mytext exec(@mytext) fetch next from mycursor into @mytextendclose mycursordeallocate mycursorend