[英]is it possible to convert all columns to varchar(500) in sql server all at time
我在數據庫中有大約600列。在創建時我用int代替了varchar.so為了使所有列都變成varchar(500),我必須寫alt命令576次,還是有什么方法可以將全部轉換為varchar( 500)。我現在使用sql server
這個查詢
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
,將結果復制到另一個查詢編輯器窗口中,然后將其翻錄。
在運行數據庫之前,請確保您位於正確的數據庫中,並在執行此操作之前先進行備份,因為這可能會立即破壞數據庫結構
嘗試執行以下操作(之前進行備份):
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,索引,檢查約束等的列 , 它無濟於事。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.