Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Converting Varchar to NVarchar?

I know when converting from nvarchar to varchar, some data will be lost/changed.

However, are there any risks of data changing when converting a varchar data type to an nvarchar?

like image 657
Curtis Avatar asked Oct 20 '11 14:10

Curtis


People also ask

Can you convert varchar to NVARCHAR?

NVARCHAR has higher precedence than the VARCHAR data type. Therefore, during the data type conversion, SQL Server converts the existing VARCHAR values into NVARCHAR.

Is varchar and NVARCHAR same?

The key difference between varchar and nvarchar is the way they are stored, varchar is stored as regular 8-bit data(1 byte per character) and nvarchar stores data at 2 bytes per character. Due to this reason, nvarchar can hold upto 4000 characters and it takes double the space as SQL varchar.

Should I use varchar or NVARCHAR?

Today's development platforms or their operating systems support the Unicode character set. Therefore, In SQL Server, you should utilize NVARCHAR rather than VARCHAR. If you do use VARCHAR when Unicode support is present, then an encoding inconsistency will arise while communicating with the database.


1 Answers

nvarchar stores unicode characters which are twice the size of varchar characters. So as long as your nvarchar is atleast twice the length of your vchar this will not be a problem.

Converting the other way could still be achieved providing you have not used any characters outside the ASCII character range (i.e. you do not have Unicode characters)

In short, make sure your nvarchar lengths are twice the size of your largest varchar value and then make the change.


As I seem to have received a couple of downvotes on this (with no explanation), I want to make it clear that when I refer to length above I mean the size, e.g. that amount of storage data required. Please note my comment below, which I will also include here:

If you are talking about changing the length with SQL then I think you should be ok to have the same length. This is because when you specify the length you do so based on the number of characters and not the actually amount of data that gets stored

like image 97
musefan Avatar answered Sep 17 '22 18:09

musefan