我在DB中有大约600列。虽然我创建了int而不是varchar.So为了使所有列都变为varchar(500)我是否必须编写alter命令576次或是否有任何方法来转换所有to varchar(500)。我现在使用sql server
答案 0 :(得分: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
,将结果复制到另一个查询编辑器窗口,然后将其翻录。
在运行之前确保您所在的数据库正确,并在之前进行备份,因为这可能会在一瞬间破坏您的数据库结构
答案 1 :(得分: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,索引,检查约束等的列没有帮助。