简体   繁体   中英

Changing nvarchar(MAX) to nvarchar(n) in database

I just changed a nvarchar(MAX) field in a table to nvarchar(250). Could someone please tell me what happens to the data if there was an entry larger than 250 characters?

My concern is not with the visible data, but what happens behind the scenes:

  • What is done to the data which overshoots the limit of that container of data?
  • I read in a few places that the table has to be deleted and re created again. Is this true and why? I didn't see any errors which the others received.
  • Is there a way to recover the truncated data after making this change? (I dont want to do it, but I'm curious)

If you have altered/changed column nvarchar(MAX) field into nvarchar(250) and you did not receive any error, it means that none on rows contains the data more than 250 characters that why SQL server successfully changed the column length and your data is accurate/complete.

If any of row contains more than 250 characters then SQL server will give you an error and alter statement will be failed. It means that data type length will not be changed.

Msg 8152, Level 16, State 13, Line 12 String or binary data would be truncated. The statement has been terminated.

While altering column length if SET ANSI_WARNINGS OFF then SQL server will change the column length without any warning and extra data will be truncated.

By Default, it is SET ANSI_WARNINGS ON to warn the user.

I think Once data is truncated it can't be recovered later.

The system should prevent you or at least warn you of possible data loss when changing column length if any row exceeds the new length.

Depending on DBMS and version, you may even not be able to change column length.

However, if you don't have any rows exceeding 250, as you said, then there should be no problem.

There is no way to recover truncated data unless you have access to a database backup that's just before the change

On a side note, regardless of what you intend to do with that change, I should suggest to avoid columns of variable-length

MySQL automatically reserves maximum-possible length for a variable-length column, regardless of whether a row is 15 characters or 45 or 250. This, as you can imagine, eventually leads to bottlenecks in the system. (Maybe you don't have a database large enough for this to show effects, but my motto is "forewarned is forearmed" )

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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