简体   繁体   English

从子查询SQL Server 2008更新

[英]Update from subquery SQL Server 2008

I have tblPatient with the county name and state name in the table. 我有tblPatient表中的县名和州名。 I have a look up table for both county name and state name and I'm trying to normalize my tblPatient, its structure is 我有一个县名和州名的查找表,我正在尝试规范我的tblPatient,它的结构是 在此输入图像描述

As you can imagine, different states sometimes share county names. 可以想象,不同的州有时会共享县名。 To deal with this I'm using the query 为了解决这个问题,我正在使用查询

select patientid, admissionDate, dischargeDate, patientState, patientCounty
from tblPatient
where patientState='AL'

I'd like to update tblPatient.patientCounty to equal tblStateCounties.countyCode where patientCounty and countyName are the same. 我想将tblPatient.patientCounty更新为等于tblStateCounties.countyCode ,其中patientCounty和countyName是相同的。

I haven't had a dummy's version of how to use rollback yet, but this looks correct to me, yet I don't want to be committed to a possibly silly error. 我还没有使用如何使用rollback的虚拟版本,但这看起来对我来说是正确的,但我不想承诺可能是愚蠢的错误。

update tblPatient
set tblPatient.patientCounty=tblStateCountes.countyCode
from 
(
select patientID, admissionDate, dischargeDate, patientState, patientCounty from tblPatient
where patientState='AL'
) as t
inner join on tblStateCounties.countyName=tblPatient.countyName

The query you wrote won't parse (you can check that easily enough) because you're missing the FROM clause in your sub query.You'd also need to JOIN on t.tblPatient and also you'd need tblPatient in your main FROM clause. 你写的查询不会解析(你可以很容易地检查),因为你在子查询中缺少FROM子句。你还需要在t.tblPatient上加入你也需要你的主要tblPatient FROM子句。

You can use the query below to update your table. 您可以使用以下查询来更新表格。

UPDATE tblPatient 
SET    tblPatient.patientCounty = tblStateCounties.countyCode 
FROM   tblPatient 
       INNER JOIN tblStateCounties 
               ON tblStateCounties.countyName = tblPatient.patientCounty 
WHERE  patientState = 'AL' 
       AND tblStateCounties.stateCode = '01'; 

You'll notice I removed the subquery and used a simple where clause. 您会注意到我删除了子查询并使用了一个简单的where子句。 Since you noted that counties can share names so you will need to filter for the tblStateCounties.stateCode as well 由于您注意到县可以共享名称,因此您还需要过滤tblStateCounties.stateCode

Also consider making a table mapping of StateNames to StateCode (if you don't have that already) 还要考虑将StateNames的表映射到StateCode(如果你还没有)

DEMO DEMO

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

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