我已将 postgresql 数据库迁移到 SQL Server 2016,其中我所有的文本列都具有 TEXT
数据类型。我意识到 TEXT
不应在 SQL Server 中使用。
是否有一个简单的查询可以将 SQL Server 中的所有文本列数据类型从 TEXT
更改为 VARCHAR(MAX)
?
我找到了这个 answer但受列名限制。我想一次完成。
select
'alter table '||table_schema||'.'||table_name||' alter column'||column_name||' type text;'
from
information_schema.columns
where
table_schema = 'public'
and column_name = 'description'
and data_type = 'text';
最佳答案
如果你只想生成命令,你可以使用这样的东西:
select
'use ' + quotename(c.table_catalog) + '; alter table '
+ quotename(c.table_schema) + '.' + quotename(c.table_name)
+ ' alter column ' + quotename(c.column_name) + ' varchar(max);'
from information_schema.columns as c
inner join information_schema.tables t
on c.table_name = t.table_name
and c.table_schema = t.table_schema
where c.data_type = 'text'
and t.table_type = 'base table'
如果要自动生成并执行:
declare @sql nvarchar(max);
set @sql = stuff((
select
char(10)+'use ' + quotename(c.table_catalog) + '; alter table '
+ quotename(c.table_schema) + '.' + quotename(c.table_name)
+ ' alter column ' + quotename(c.column_name) + ' varchar(max);'
from information_schema.columns as c
inner join information_schema.tables t
on c.table_name = t.table_name
and c.table_schema = t.table_schema
where c.data_type = 'text'
and t.table_type = 'base table'
for xml path (''), type).value('.','nvarchar(max)')
,1,1,'')
select CodeGenerated = @sql; /* preview code generated */
--exec sp_executesql @sql; /* uncomment to execute after previewing */
rextester 演示:http://rextester.com/AIYG12069
https://stackoverflow.com/questions/43666445/