如何使用where子句中的join编写更新

时间:2014-01-23 20:58:58

标签: sql sql-server-2008-r2

我正在尝试运行此SQL来更新表。问题是我需要一个连接才能更新正确的记录。这是我到目前为止所提出的:

Update UserProfile 
  set UserProfile.PropertyValue = 'Test'
  join ProfilePropertyDefinition
      on ProfilePropertyDefinition.Id = UserProfile.PropertyDefinitionId
  where UserProfile.UserId = 11
  and ProfilePropertyDefinition.PortalID = 0
  and ProfilePropertyDefinition.PropertyName = 'Address1'
  and ProfilePropertyDefinition.PropertyCategory = 'Address'

这是我得到的消息:

关键字“join”附近的语法不正确。

3 个答案:

答案 0 :(得分:2)

你快到了,你忘记了from条款:

Update UserProfile 
  set UserProfile.PropertyValue = 'Test'
  from UserProfile
  join ProfilePropertyDefinition
      on ProfilePropertyDefinition.Id = UserProfile.PropertyDefinitionId
  where UserProfile.UserId = 11
  and ProfilePropertyDefinition.PortalID = 0
  and ProfilePropertyDefinition.PropertyName = 'Address1'
  and ProfilePropertyDefinition.PropertyCategory = 'Address'

答案 1 :(得分:1)

Update UserProfile 
  set UserProfile.PropertyValue = 'Test'
from UserProfile
  join ProfilePropertyDefinition
      on ProfilePropertyDefinition.Id = UserProfile.PropertyDefinitionId
  where UserProfile.UserId = 11
  and ProfilePropertyDefinition.PortalID = 0
  and ProfilePropertyDefinition.PropertyName = 'Address1'
  and ProfilePropertyDefinition.PropertyCategory = 'Address'

您必须在from子句中重复该表进行更新 - 此语法的事件看起来有点奇怪。

答案 2 :(得分:1)

您缺少FROM子句:

Update a 
set    PropertyValue = 'Test'
FROM   UserProfile as a 
       inner join ProfilePropertyDefinition as b
       on b.Id = a.PropertyDefinitionId
where  a.UserId = 11
       and b.PortalID = 0
       and b.PropertyName = 'Address1'
       and b.PropertyCategory = 'Address';