Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Changing a data column from varchar(max) to nvarchar(max) in SQL Server 2008

I have to change the data type in a SQL Server 2008 table from varchar(max) to nvarchar(max). This table has data in it. Is there a way to change the data type without losing the data?

like image 307
Blade3 Avatar asked May 15 '12 20:05

Blade3


People also ask

What is nvarchar Max SQL Server 2008?

nvarchar [ ( n | max ) ] max indicates that the maximum storage size is 2^30-1 characters (2 GB). The storage size is two times n bytes + 2 bytes. For UCS-2 encoding, the storage size is two times n bytes + 2 bytes and the number of characters that can be stored is also n.

What is the difference between VARCHAR Max and nvarchar Max?

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.

Why you shouldn't use VARCHAR Max?

You cannot create regular index on a VARCHAR(MAX) column. So, if you want a indexed string column then you have to go for VARCHAR(N). There is no direct way to restrict the length of the string stored in a VARCHAR(MAX) column. On the other hand, using VARCHAR(1-8,000), you can limit the string saved in the column.


1 Answers

You can just use standard syntax to alter the table:

ALTER TABLE some_table ALTER COLUMN some_column nvarchar(max)

You will probably want to rebuild any indices however, to make sure they work as expected.

like image 92
PinnyM Avatar answered Sep 28 '22 08:09

PinnyM