0

我在 DB 中有大约 600 列。在创建时我创建了 int 而不是 varchar。所以为了使所有列都变为 varchar(500),我是否必须编写 alter 命令 576 次,或者有什么方法可以将所有列转换为 varchar( 500).我现在使用 sql server

4

2 回答 2

2

这个查询

select o.object_id, o.name, c.column_id, c.name
from sys.columns c
  inner join sys.objects o on o.object_id=c.object_id
where c.system_type_id = (select system_type_id from sys.types where name='int')
  and o.type='U'
  and o.name = 'SomeTableName' -- if you want to filter by table

将为您提供数据库中使用int数据类型定义的所有列。按摩 select 语句以生成正确的alter语法,如下所示:

select 'alter table '+ o.name +' alter column '+ c.name +' varchar(500);'
from sys.columns c
  inner join sys.objects o on o.object_id=c.object_id
where c.system_type_id = (select system_type_id from sys.types where name='int')
  and o.type='U'
  and o.name = 'SomeTableName' -- if you want to filter by table

,将结果复制到另一个查询编辑器窗口中,然后让它翻录。

在运行之前确保您在正确的数据库中,并在之前进行备份,因为这可能会立即破坏您的数据库结构

于 2013-08-14T09:41:47.873 回答
1

尝试以下(之前做备份):

declare @commands table (SqlStatement nvarchar(max))

insert into @commands (SqlStatement)
select 'alter table ' + quotename(s.name) + '.' + quotename(T.name)
    + ' alter column ' + quotename(c.name) + ' varchar(500)'
from sys.tables T
    join sys.schemas S on S.schema_id = T.schema_id
    join sys.columns c on c.object_id = T.object_id
where c.name = 'ColName' -- specify conditions to identify tour columns
order by S.name, T.name, c.name

declare csSql cursor local fast_forward for
select SqlStatement from @commands

open csSql

declare @sql nvarchar(max)

fetch next from csSql into @sql
while @@fetch_status = 0 begin

    begin try
        print @sql
        --inspect ouput and uncomment exec if you sure
        --exec(@sql)
    end try
    begin catch
        print error_message()
    end catch

    fetch next from csSql into @sql
end

close csSql
deallocate csSql

exec当您确定输出正常时,更改条件以识别您的列并取消注释。

但是,对于参与 PK、FK、索引、检查约束等的列,它不会帮助您。

于 2013-08-14T09:42:01.923 回答