[英]How to Change All Sql Columns of One DataType into Another
我有一個數據庫 ( Sql Server 2005
),其中有幾十個tables
,每個表都有許多columns
(平均 10-20),數據類型設置為nvarchar(max)
。 這絕對會降低性能(其中一些列用於joins
,一些表有 100K+ 行)。 我想將所有這些列更改為varchar(250)
。 自動化這個的最好方法是什么? (我可以使用Management Studio
,或者我可以創建一個實用程序來通過可以訪問數據庫的ASP.net
網站執行此操作,以更容易的為准)。
這是一個工作腳本,它使用INFORMATION_SCHEMA.COLUMNS
查找所有*varchar(max)
列並將它們轉換為varchar(255)
:
declare @schema nvarchar(255)
declare @table nvarchar(255)
declare @col nvarchar(255)
declare @dtype nvarchar(255)
declare @sql nvarchar(max)
declare maxcols cursor for
select
c.TABLE_SCHEMA,
c.TABLE_NAME,
c.COLUMN_NAME,
c.DATA_TYPE
from
INFORMATION_SCHEMA.COLUMNS c
inner join INFORMATION_SCHEMA.TABLES t on
c.TABLE_CATALOG = t.TABLE_CATALOG
and c.TABLE_SCHEMA = t.TABLE_SCHEMA
and c.TABLE_NAME = t.TABLE_NAME
and t.TABLE_TYPE = 'BASE TABLE'
where
c.DATA_TYPE like '%varchar'
and c.CHARACTER_MAXIMUM_LENGTH = -1
open maxcols
fetch next from maxcols into @schema, @table, @col, @dtype
while @@FETCH_STATUS = 0
begin
set @sql = 'alter table [' + @schema + '].[' + @table +
'] alter column [' + @col + '] ' + @dtype + '(255)'
exec sp_executesql @sql
fetch next from maxcols into @schema, @table, @col, @dtype
end
close maxcols
deallocate maxcols
這是我唯一容忍的游標用法,但它是一個很好的用法。 本質上,它找到所有*varchar(max)
,構建alter
語句,然后使用sp_executesql
執行它。
享受!
您可以使用以下方法輕松找到它們:
select 'alter table ' + quotename(o.name) + ' alter column ' + quotename(c.name) + ' varchar(250); '
from sys.columns c
join
sys.objects o
on o.object_id = c.object_id
where o.type = 'U'
and c.user_type_id = 231
and c.max_length = -1
所以現在只需獲取查詢結果並運行它。
搶
我認為完成此任務的最佳方法是為當前數據庫生成腳本,然后將文本文件中的 nvarchar(max) 替換為 varchar(250),然后創建新數據庫。 之后使用導入/導出實用程序將數據傳輸到新數據庫。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.