5

I need suggestions on how I would best go about changing a column's data type from varchar to nvarchar for a table which has 500 million records.

Thanks in advance.

marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
Panda1122
  • 101
  • 1
  • 10

3 Answers3

5

You just need to issue an ALTER TABLE statement

ALTER TABLE YourTable ALTER COLUMN YourColumn nvarchar({required length});

You'll need to replace the section in braces ({}) and replace with your object names.

Thom A
  • 88,727
  • 11
  • 45
  • 75
  • It took more than 6 hours to do it. looking for a faster approach. – Panda1122 Feb 26 '19 at 09:33
  • Have a look a Alexander's answer, @Panda1122. He raises reasons to why this is going to be slow, but there's not a huge amount you can do about it; you're making a fundamental change to the datatype so the entire column needs to be rewritten. – Thom A Feb 26 '19 at 09:51
4

for a table which has 500 million records.

While Larnu answer is very much correct, due to size of the table I would like to point to this thread:

Change datatype varchar to nvarchar in existing SQL Server 2005 database. Any issues?

and url: http://rusanu.com/2011/10/20/sql-server-table-columns-under-the-hood/

The change will add a new NVARCHAR column, it will update each row copying the dta from the old VARCHAR to the new NVARCHAR column, and then it will mark the old VARCHAR column as dropped. IF the table is large, this will generate a large log, so be prepared for it.

Unfortunately, VARCHAR()->NVARCHAR() is not metadata only change, so not like INT->BIGINT

Therefore, a suggestion to run a change at a maintenance window with further removal of a column that is marked as "deleted":

DBCC CLEANTABLE 
-- or
ALTER TABLE ... REBUILD
Alexander Volok
  • 5,630
  • 3
  • 17
  • 33
2

So, all what i did was, 1. Create a new table with nvarchar for required column 2. copy data from existing table to new table using ssis. 3. Create constraints and indexes on new table. All these steps can be done when the app is still up and running 4. Rename existing table to _Old and rename new table to existing table's name Above step hardly takes a second and is the only step when the app is down.

Like this i was able to reduce the app down time and successfully changed column data type.

Panda1122
  • 101
  • 1
  • 10