简体   繁体   English

SQL Case Statement 基于列值

[英]SQL Case Statement Based on Column value

The 'patient' table needs to be updated from the 'history' table.需要从“历史”表中更新“患者”表。 The patient table has all of the history in a single row while the history table has one type of history per row.患者表在一行中包含所有历史记录,而历史记录表每行包含一种类型的历史记录。 How can I use a conditional something like below (my best attempt) to update the right column based on the history_code value which indicates what type of history data it is.我如何使用类似下面的条件(我的最佳尝试)来根据 history_code 值更新右列,该值指示它是什么类型的历史数据。

Any help would be appreciated任何帮助,将不胜感激

UPDATE AUS.dbo.patient SET 

    CASE 
    WHEN history_code = 'surgery' THEN surh = smh.condition
    WHEN history_code = 'social' THEN soch = smh.condition
    WHEN history_code = 'medical' THEN medh = smh.condition
    WHEN history_code = 'family' THEN famh = smh.condition
    WHEN history_code = 'ocular' THEN obsh = smh.condition
    END

FROM history AS smh
LEFT JOIN patient AS sp
    ON smh.patient_id = sp.patient_id
LEFT JOIN AUS.dbo.u_master AS um
    ON sp.old_patient_id = um.filenumber COLLATE Latin1_General_CS_AS
WHERE patient.fk_master_masterid = um.masterID```

CASE is an expression not a statement and as such can only return a scalar value, not conditionally run a statement. CASE表达式而不是语句,因此只能返回标量值,不能有条件地运行语句。 Instead you need one CASE per column you wish to update, either modifying the value or leaving it the same as per your conditions.相反,您希望更新的每一列都需要一个CASE ,根据您的条件修改值或使其保持不变。 Here is one column:这是一列:

surh =
    CASE
    WHEN history_code = 'surgery' THEN smh.condition
    ELSE surh
    END

I highly recommend reading the documentation when unsure about some functionality.我强烈建议在不确定某些功能时阅读文档

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

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