我对SQL很新,对UPDATE查询有疑问。我正在使用SQL Server 2008 R2。我写了以下SELECT查询:
SELECT res.labresultcat_id, res.patient_id, lab.test_performed,
lab.result_status, lab.result_value, lab.abnormal_flag, res.recorded_on,
res.cat_test_name, res.results_to, usr.last_name, res.result_viewed
FROM dbo.med_labresultcat res
INNER JOIN dbo.med_labresult lab
ON res.labresultcat_id = lab.labresultcat_id
LEFT JOIN dbo.res_user usr
ON res.results_to = usr.resource_id
WHERE lab.result_status = 'F' AND usr.last_name = 'Smith'
AND res.result_viewed is NULL
结果看起来像这样:
patient_id result_id test_performed abnormal_flag recorded_on results_to
0001 0045 ABC N 4/1/2013 14
0001 0045 CBS A 4/1/2013 14
0002 0061 NBC N 4/3/2013 13
0002 0061 MST N 4/3/2013 13
0003 0090 ABC H 4/20/2013 10
0003 0090 MST N 4/20/2013 10
所以,我写了以下UPDATE查询:
;WITH lab AS (SELECT res.labresultcat_id, res.patient_id, lab.test_performed,
lab.result_status, lab.result_value, lab.abnormal_flag, res.recorded_on,
res.cat_test_name, res.results_to, usr.last_name, res.result_viewed
FROM dbo.med_labresultcat res
INNER JOIN dbo.med_labresult lab
ON res.labresultcat_id = lab.labresultcat_id
LEFT JOIN dbo.res_user usr
ON res.results_to = usr.resource_id
WHERE lab.result_status = 'F' AND usr.last_name = 'Smith'
AND res.result_viewed is NULL AND (abnormal_flag = 'N' OR abnormal_flag is NULL))
UPDATE lab SET results_to = '184'
上述查询确实更新了分配给实验室结果的人员。但是,如果具有相同result_id的所有结果都是'N'或NULL,我只需要更新results_to字段。
任何帮助,如果非常感谢。谢谢!
答案 0 :(得分:0)
只需在update语句中附加一个where子句,并在where语句中执行匹配的子句。