tags:

views:

39

answers:

2

Hi Guys,

Whats going to be the easiest way to migrate my data in the following situation:

Table A: ANIMAL

ANIMAL_ID (PK,IDENTITY)
CAT_NAME
DOG_NAME
BIRD_NAME
FISH_NAME

Table B: ANIMAL_NEW

ANIMAL_ID (PK,IDENTITY)
ANIMAL_TYPE(INT)
ANIMAL_NAME

I've changed the design, so instead of having 4 of the same table columns, I introduced an ANIMAL_TYPE Column, which will be an enum {Cat=0, Dog=1, Bird=2, Fish=3}...

Whats the quickest way to migrate the data, taking into account that if CAT_NAME or DOG_NAME is empty, that no record should be created in the new table.

Thanks

+1  A: 

You can just do 4 separate statements:

INSERT INTO animal_new (animal_id, animal_type, animal_name)
SELECT
  animal_id, 0, cat_name
FROM
  animal
WHERE
  cat_name IS NOT NULL

INSERT INTO animal_new (animal_id, animal_type, animal_name)
SELECT
  animal_id, 1, dog_name
FROM
  animal
WHERE
  dog_name IS NOT NULL

(etc)

This is assuming that only one of cat_name, dog_name, bird_name, fish_name is ever non-NULL in your original design. If that's not the case, then you're going to have trouble with the new animal_id primary key...

Dean Harding
Yea thats the thing, sometimes none of them have values, but the row still exists, ea: has an ID.
FaNIX
+1  A: 

You could use simple CASE:

INSERT INTO animal_new(animal_id, animal_type, animal_name)
SELECT animal_id, 
  animal_type =
  CASE 
    WHEN LEN(cat_name) > 0 THEN 1
    WHEN LEN(dog_name) > 0 THEN 2
    WHEN LEN(bird_name) > 0 THEN 3
    WHEN LEN(fish_name) > 0 THEN 4
    ELSE 5 
  END,
  animal_name =
  CASE 
    WHEN LEN(cat_name) > 0 THEN cat_name
    WHEN LEN(dog_name) > 0 THEN dog_name
    WHEN LEN(bird_name) > 0 THEN bird_name
    WHEN LEN(fish_name) > 0 THEN fish_name
    ELSE ''
  END
FROM animal;

The ELSE in both cases is when none of the animal names are set.

jimmy_keen
Awesome, thanks :)
FaNIX