简体   繁体   English

将Nvarchar(max)转换为nvarchar的最佳/最有效方法(30)

[英]Best/most efficient way to convert Nvarchar(max) to nvarchar (30)

I was wondering if anyone could give me a pointer with the problem. 我想知道是否有人可以给我指出这个问题的指针。 I assume others have experienced this before and was wondering what is the most efficient. 我假设其他人以前曾经经历过,并且想知道什么是最有效的。

I have production data that is taking rather long to process, mainly because we haven't set indexes on an ID field. 我的生产数据需要花费相当长的时间来处理,主要是因为我们尚未在ID字段上设置索引。

The ID field is currently a nvarchar(max), so it can't be indexed. ID字段当前为nvarchar(max),因此无法编制索引。 This ID is never longer than 30 characters, and I would therefore like to change the data type to nvarchar(30). 该ID的长度不得超过30个字符,因此我想将数据类型更改为nvarchar(30)。 However, I've noticed that using a statement such as: 但是,我注意到使用了如下语句:

ALTER TABLE [dbo].[Table] ALTER COLUMN [Column1] NVARCHAR ( 30 ) NOT NULL

Takes a significant amount of time for the smaller tables already. 对于较小的表,已经花费了大量时间。 I'm worried it might not even work for the larger tables, as the DiskIO is incredibly high for the smaller tables already. 我担心它甚至可能不适用于较大的表,因为DiskIO对于较小的表已经很高了。

Would the following be faster and could it work? 以下内容会更快并且可以工作吗?

  • Create a new column with the nvarchar(30) data type. 使用nvarchar(30)数据类型创建一个新列。
  • Then copy the data from the nvarchar(max) column to the nvarchar(30) column. 然后将数据从nvarchar(max)列复制到nvarchar(30)列。
  • Then remove the nvarchar(max) column. 然后删除nvarchar(max)列。
  • Then rename the nvarchar(30) column to the name of the nvarchar(max) column? 然后将nvarchar(30)列重命名为nvarchar(max)列的名称?

Does anyone have any suggestions as to what might be even better? 有没有人对更好的建议?

Any pointers/help would be appreciated! 任何指针/帮助将不胜感激!

We solve a similar issue by creating an empty new column (NULL) and updating in batches 我们通过创建一个空的新列(NULL)并批量更新来解决类似的问题

update top (5000) myTable --parentheses are mandatory, set a small number to avoid transaction log issues
set newCol = oldCol -- or left(oldCol,30) not sure your data
where newCol is null

go 10000 --runs 10,000 times, set accordingly to your rows amount, this covers 50 million rows(5,000x10,000) 

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

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