简体   繁体   English

T-SQL:将数据从一个表移动到另一个表

[英]T-SQL: Move data from one table to another

Whats going to be the easiest way to migrate my data in the following situation: 在以下情况下,最简单的方法就是迁移数据:

Table A: ANIMAL 表A:动物

ANIMAL_ID (PK,IDENTITY)
CAT_NAME
DOG_NAME
BIRD_NAME
FISH_NAME

Table B: ANIMAL_NEW 表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}... 我已经更改了设计,因此,我不再使用4个相同的表列,而是引入了ANIMAL_TYPE列,它将是一个枚举{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. 考虑到如果CAT_NAMEDOG_NAME为空,则不应在新表中创建任何记录,这是迁移数据的最快方法。

Thanks 谢谢

You can just do 4 separate statements: 您可以只做4个单独的语句:

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. 这是假设在原始设计中,只有cat_name,dog_name,bird_name,fish_name之一为非NULL If that's not the case, then you're going to have trouble with the new animal_id primary key... 如果不是这种情况,那么您将无法使用新的animal_id主键...

You could use simple CASE : 您可以使用简单的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. 两种情况下的ELSE都是未设置任何动物名称的情况。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM