Sun
Sun

Reputation: 4718

Update column data type and update the data

I have a SQL server database design problem.

I have an existing database table with hundreds of records in there. One of the columns is of type NVARCHAR but it should be an integer with all the data in a lookup table.

Is there any clever way in SQL Server to get the data out of the column and into a new lookup table, change the datatype of the column and update the values with the correct ID from the new lookup table??

Thanks in advance.

I'm using SQL Server 2008

Upvotes: 0

Views: 606

Answers (1)

Damien_The_Unbeliever
Damien_The_Unbeliever

Reputation: 239714

No, you have to do it as 3 steps:

  1. Insert the values into the new lookup table
  2. Update the current rows so that the nvarchar column now contains appropriate ID values from the lookup table
  3. Change the column definition to int
  4. (4th of 3 :-)) create a foreign key constraint between this column and the ID column of the lookup table.

Thankfully, int values should always be able to fit in an nvarchar, unless it's an especially small one (in which case you'll have to expand it first).

Upvotes: 3

Related Questions