简体   繁体   English

将所有NCHAR列转换为数据库或表中的NVARCHAR列

[英]Convert all NCHAR columns to NVARCHAR columns in a database or table

I have a database that contains a lot of NCHAR(n) columns. 我有一个包含大量NCHAR(n)列的数据库。 Some of these columns are simple properties, but some are also primary-keys or foreign keys. 其中一些列是简单属性,但有些也是主键或外键。

There are many tables and columns and a huge amount of test data. 有许多表和列以及大量的测试数据。

What is the best way to convert every NCHAR(n) column to a NVARCHAR(n) column of the same length and trim its content while doing so? 将每个NCHAR(n)列转换为相同长度的NVARCHAR(n)列并在其中修剪其内容的最佳方法是什么?

If you can think of anything better than changing the column in the designer, remembering the column name and trimming it in a script window, please post it as an answer. 如果你能想到比更改设计器中的列更好的事情,记住列名并在脚本窗口中修剪它,请将其作为答案发布。

Something like this would do the trick I think (unless any are primary keys and then you will get an error - I would suggest that you manually do the primary keys in the designer in your case because to alter them you have to drop the constraints etc and that gets a bit tricky)... 像这样的东西会做我认为的技巧(除非任何主键然后你会得到一个错误 - 我建议你在你的情况下手动执行设计器中的主键,因为要改变它们你必须放弃约束等这有点棘手)...

It gets all the table names, column names and sizes for all the columns that are nchar and for each performs an alter statement to change the column type and then an update that trims the data. 它获取所有nchar列的表名,列名和大小,并为每个列执行alter语句以更改列类型,然后执行修剪数据的update

There may be a more performant way to do it but if you are only doing it once perhaps this will be ok (oh, change the databaseName bit to the name of your database)... 可能有一种更高效的方法可以做到这一点,但如果你只做一次也许这样就可以了(哦,将databaseName位更改为databaseName的名称)...

use databaseName

declare @tn nvarchar(128)
declare @cn nvarchar(128)
declare @ln int

declare @sql as nvarchar(1000)

declare c cursor for 
    select table_name,column_name,character_maximum_length 
    from information_schema.columns 
    where data_type ='nchar' and 
        TABLE_NAME not in (select TABLE_NAME from INFORMATION_SCHEMA.VIEWS)

open c
fetch next from c into @tn, @cn, @ln

while @@FETCH_STATUS = 0
begin

    set @sql = 'alter table ' + @tn + ' alter column ' 
        + @cn + ' nvarchar(' + convert(nvarchar(50), @ln) + ')'
    exec sp_executesql @sql

    set @sql = 'update ' + @tn + ' set ' + @cn + ' = LTRIM(RTRIM(' + @cn + '))'
    exec sp_executesql @sql

    fetch next from c into @tn, @cn, @ln
end

close c
deallocate c

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM