[英]Changing all varchar columns in a SQL Server database to nvarchar
I am trying to update all varchar
columns in a database to nvarchar
without losing the data. 我正在尝试将数据库中的所有
varchar
列更新为nvarchar
而不会丢失数据。
I have the following query: 我有以下查询:
select *
from INFORMATION_SCHEMA.COLUMNS
where DATA_TYPE = 'varchar'
How do I modify this to update the columns it finds and have that reflected throughout the database? 如何修改它以更新它找到的列并在整个数据库中反映出来?
I would use the SQL Server specific sys
catalog views, and what I'd do is just simply create the T-SQL statements it takes to change those data types - something like this: 我将使用特定于SQL Server的
sys
目录视图,而我要做的只是简单地创建更改这些数据类型所需的T-SQL语句-像这样:
SELECT
t.name, s.name, c.name,
'ALTER TABLE ' + s.name + '.' + t.Name + ' ALTER COLUMN ' + c.name + ' NVARCHAR(' +
CASE
WHEN c.max_length = -1 THEN 'MAX'
WHEN c.max_length > 4000 THEN 'MAX'
ELSE CAST(c.max_length AS VARCHAR(10)) + ');'
END
FROM
sys.tables t
INNER JOIN
sys.schemas s ON t.schema_id = s.schema_id
INNER JOIN
sys.columns c ON c.object_id = t.object_id
INNER JOIN
sys.types ty ON c.system_type_id = ty.system_type_id
WHERE
ty.name = 'VARCHAR'
AND c.is_computed = 0
Run on the AdventureWorks
database, this will output something like: 在
AdventureWorks
数据库上运行,这将输出如下内容:
ALTER TABLE Sales.SalesOrderHeader ALTER COLUMN CreditCardApprovalCode NVARCHAR(15);
ALTER TABLE Person.Password ALTER COLUMN PasswordHash NVARCHAR(128);
ALTER TABLE Person.Password ALTER COLUMN PasswordSalt NVARCHAR(10);
which you can then copy from the output grid into a new query window and execute. 然后可以将其从输出网格复制到新的查询窗口并执行。
Note: running your original script against AdventureWorks
showed me that in that case, one of the columns is computed and can therefore not be modified by simply using a ALTER TABLE ... ALTER COLUMN ....
statement - that's why I'm excluding computed columns in my script shown here. 注意:在
AdventureWorks
运行原始脚本会告诉我,在这种情况下,其中一列是经过计算的 ,因此不能仅通过使用ALTER TABLE ... ALTER COLUMN ....
语句进行修改-这就是为什么我不包括在内此处显示的脚本中的计算列。
If you really insist, you could also turns this SQL statement of mine into the "heart" of a cursor and then iterate over the T-SQL statement to modify the table, and execute those using EXEC(...)
or EXEC sp_executesql
如果确实坚持,也可以将我的SQL语句转换为游标的“心脏”,然后遍历T-SQL语句以修改表,并使用
EXEC(...)
或EXEC sp_executesql
执行那些语句EXEC(...)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.