Update Field based on another table's values

。_饼干妹妹 提交于 2020-01-06 08:25:41

问题


Is there a more elegant way to write the following Microsoft SQL Server 2008 command?

UPDATE TableB
SET TableBField2=0
WHERE TableBID IN(
     SELECT TableBID 
     FROM TableB
     JOIN TableA on TableB.TableAID=TableA.TableAID
     WHERE TableBField2 < 0
     AND TableAField1 = 0
)

In plain speak, what I'm doing is updating a table based on the value of a field in a joined table. I wonder if my use of IN() is considered inefficient.


回答1:


This should be more efficient:

UPDATE TableB b
SET TableBField2=0
WHERE exists (
     SELECT 1
     FROM TableA
     WHERE b.TableAID=TableA.TableAID
     AND b.TableBField2 < 0
     AND TableAField1 = 0
)



回答2:


You can try something like this

UPDATE TableB
SET Field2 = 0
FROM    TableB b INNER JOIN
        TableA a ON b.TableB.TableAID=a.TableAID
WHERE b.Field2 < 0     
AND a.Field1 = 0


来源:https://stackoverflow.com/questions/1764690/update-field-based-on-another-tables-values

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!