sql - 在 SQL Server 中将所有表数据类型从文本更改为 varchar

我已将 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/

相关文章:

angular - HTML5 Websql - 如何与 Ionic 3 和 Angular 4 一

perl - 在 Perl 中打印哈希值

c# - Unity Particle Collider 与粒子

vim - 将行合并到 vim 中的段落

linux - 错误 "caution: filename not matched"- 解压缩命令

r - 在 shinyapps.io 中部署 R 应用程序 - "Error:parsing man

arrays - Swagger 的对象数组

django - 值错误 : Cannot use Queryset for "": Use a Q

qt - 对 `dlsym' 的 undefined reference

php - 当要比较的元数据是序列化数组时,Wordpress meta_query 值数组?