日期:2014-05-18  浏览次数:20750 次

批量修改表结构
我想把某个数据库中所有表的字段类型为varchar的够改为nvarchar
比如说原数据库中字段为varchar(10)的改为nvarchar(20)
原数据库中字段为varchar(20)的改为nvarchar(40)
只修改自己创建的表,不修改系统表
请问有sql语句能修改吗?

------解决方案--------------------
SQL code

declare @tb_name Nvarchar(120)
declare @column_name Nvarchar(120)
declare @max_len int
declare @sql nvarchar(max)


declare cur_cur cursor for 
select b.name, a.name as column_name ,a.max_length from sys.all_columns a join sys.sysobjects b on a.object_id=b.id and b.xtype='U' 
join sys.types c on a.user_type_id=c.user_type_id and c.name ='varchar' and c.user_type_id =167 and (a.max_length =10 or a.max_length =20)
open cur_cur
fetch next from cur_cur into @tb_name,@column_name,@max_len
while @@FETCH_STATUS =0
begin
    if @max_len =10
        begin
            set @sql=N'alter table '+@tb_name+' alter column '+@column_name+' nvarchar(20)'
        end
    if @max_len=20
        begin
            set @sql=N'alter table '+@tb_name+' alter column '+@column_name+' nvarchar(40)'
        end
    EXEC SP_EXECUTESQL @SQL
    fetch next from cur_cur into @tb_name,@column_name,@max_len
end
close cur_cur
deallocate cur_cur