带有CASE语句的SQL Update

时间:2014-02-07 15:04:45

标签: sql sql-server sql-update

我将使用示例表。

tblAnimal:

---------------------------------
|Animal    | Colour |  Gender   |
---------------------------------
|Dog       |        |           |
---------------------------------

tblDescription:

-------------------------------
| Animal |  ID  | Description |
-------------------------------
|  Dog   |   1  |    Male     |
-------------------------------
|  Dog   |  92  |   White     |
-------------------------------

所以我想更新tblAnimal,以便填充颜色和性别。

我使用了代码

UPDATE tblAnimal
SET Colour = CASE WHEN tblDescription.ID = 92 THEN tblDescription.Description END,
    Gender = CASE WHEN tblDescription.ID = 1 THEN tblDescription.Description END
FROM tblDescription INNER JOIN tblAnimal 
    ON tblDescription.Animal = tblAnimal.Animal

但它不起作用。 tblAnimal中的两列都保持为NULL。看起来SQL Server只检查tblDescription中的第一行。

我如何编写此UPDATE语句,以便颜色和性别都是tblDescription中的内容?

修改

谢谢大家的解决方案!是的,表需要进行规范化,但这仅仅是为了在UPDATE语句中提出我的问题。

再次感谢大家。

4 个答案:

答案 0 :(得分:1)

试试这个:

UPDATE tblAnimal a
SET
    a.Colour = (SELECT d.Description d FROM tblDescription d WHERE d.Animal = a.Animal AND ID = 92),
    a.Gender = (SELECT d.Description d FROM tblDescription d WHERE d.Animal = a.Animal AND ID = 1)

答案 1 :(得分:1)

Create table tblDescription(
Animal varchar(20),
ID int,
Description varchar(20)
)

Insert into tblAnimal(Animal)
values ('Dog')

Insert into tblDescription
Select 'Dog',1,'Male' union all
Select 'Dog',92,'White'

Select * from tblAnimal

Select * from tblDescription

---Update

Update a
SET Colour = (Select d.description from tbldescription d where d.id =92),
Gender = (Select d.description from tbldescription d where d.id =1)

From tblAnimal a inner join
tblDescription d on d.Animal =a.Animal

注意:     这样可行,但我要做的是对tbldescription进行规范化。

答案 2 :(得分:0)

另一种方式:

UPDATE tblAnimal
    SET colour = (select  Description from  tblDescription where ID = 92),
        Gender = (select  Description from  tblDescription where ID = 1)

答案 3 :(得分:0)

您需要在tblAnimal中拥有ID引用才能获得与tblDescription的关联。

tblAnimal:

---------------------------------
|Animal | ID   | Colour |  Gender|
---------------------------------
|Dog    |  1  |         |       |
---------------------------------
|Dog    |  92 |         |       |
---------------------------------

然后你可以运行:

UPDATE 
  tblAnimal as a
SET
  Colour = (SELECT Description from tblDescription x WHERE x.id = a.id),
  Gender = (SELECT Description FROM tblDescription x WHERE x.id = a.id)