从另一个选定的表更新一个表

时间:2014-06-09 07:08:47

标签: sql-server

我从表中选择一列,然后按select case生成第二列:

(select Id , case
when education=0 then '0::ALL'
when education=1 then '1::HIGH_SCHOOL'
when education=2 then '2::UNDERGRAD'
when education=3 then '3::ALUM'
when education=4 then '4::HIGH_SCHOOL_GRAD'
when education=5 then '5::SOME_COLLEGE'
when education=6 then '6::ASSOCIATE_DEGREE'
when education=7 then '7::IN_GRAD_SCHOOL'
when education=8 then '8::SOME_GRAD_SCHOOL'
when education=9 then '9::MASTER_DEGREE'
when education=10 then '10::PROFESSIONAL_DEGREE'
when education=11 then '11::DOCTORATE_DEGREE'
when education=12 then '12::UNSPECIFIED'
end as myeducation
from ids_table where Id = '4fcc-a519-15db04651b91')

假设它返回:

------------------------------------------------
|         Id                 myeducation       |
|  4fcc-a519-15db04651b91,   9::MASTER_DEGREE  |
------------------------------------------------

在同一个表(ids_table)中,我有一个空列被称为:allEducations

我想设置allEducations = myeducation,其中id(我创建的上面的表格)等于表格的id(ids_table)

之前:

ids_table:
  ----------------------------------------------
|         Id                 allEducation       |
|  4fcc-a519-15db04651b91,                      |
------------------------------------------------

后:

  ----------------------------------------------
|         Id                   allEducation     |
|  4fcc-a519-15db04651b91,   9::MASTER_DEGREE   |
------------------------------------------------

我尝试过这样的事情:

`;WITH b AS (THE SQL QUERY ABOVE) update ids_table c set c.allEducations = b.myeducation where c.id = b.id'

任何帮助表示赞赏!

1 个答案:

答案 0 :(得分:1)

这应该足够了:

begin tran updateEducation

update ids_table set allEducations = 
    case
    when education=0 then '0::ALL'
    when education=1 then '1::HIGH_SCHOOL'
    when education=2 then '2::UNDERGRAD'
    when education=3 then '3::ALUM'
    when education=4 then '4::HIGH_SCHOOL_GRAD'
    when education=5 then '5::SOME_COLLEGE'
    when education=6 then '6::ASSOCIATE_DEGREE'
    when education=7 then '7::IN_GRAD_SCHOOL'
    when education=8 then '8::SOME_GRAD_SCHOOL'
    when education=9 then '9::MASTER_DEGREE'
    when education=10 then '10::PROFESSIONAL_DEGREE'
    when education=11 then '11::DOCTORATE_DEGREE'
    when education=12 then '12::UNSPECIFIED'
    end

---- if it is not good
-- rollback 

---- if it is good
-- commit