SQL Server:从连接的表中更新多个记录

时间:2015-01-14 04:51:55

标签: sql sql-server tsql sql-server-2008r2-express

我在测试环境中使用SQL Server 2008 R2 Express并在生产中使用完整版。 我写了一个select语句,找到我要更新的所有记录。其中约有1200个。 它连接多个表,选择基于多个字段。

我想要做的是将其转换为更新语句,其中所有匹配的记录都已更新相同的字段,即dFinalised设置为' 2015-01-14 00:00:00.000'

运行更新查询时收到以下错误

  

子查询返回的值超过1。当子查询遵循=,!=,<,< =,>,> =或子查询用作表达式时,不允许这样做。

我希望我不得不以某种方式筑巢,但我找不到足够简单的例子。

提前致谢 大卫

select语句非常简单

SELECT lMeetingRegisterID
      ,sPlanNumber
      ,sName
      ,sDescription
      ,dMeeting
      ,sMeetingTime
      ,bManaged

  FROM [Strata].[dbo].[MeetingRegister]
  inner Join MeetingType on MeetingRegister.lMeetingTypeID = meetingtype.lMeetingTypeID
  inner Join OwnersCorporation on MeetingRegister.lOwnersCorporationID = OwnersCorporation.lOwnersCorporationID
  inner Join tbluser on OwnersCorporation.lUserID = tblUser.lUserID

  WHERE dFinalised = '1900-01-01 00:00:00.000'
  AND dMeeting < '2014-07-01 00:00:00.000' 
  AND bManaged != 'N'

以下是我对更新查询的尝试。

Update dbo.MeetingRegister
set dFinalised = '2015-01-14 00:00:00.000'
from dbo.MeetingRegister
  inner Join MeetingType on MeetingRegister.lMeetingTypeID = meetingtype.lMeetingTypeID
  inner Join OwnersCorporation on MeetingRegister.lOwnersCorporationID = OwnersCorporation.lOwnersCorporationID
  inner Join tbluser on OwnersCorporation.lUserID = tblUser.lUserID
Where dFinalised = '1900-01-01 00:00:00.000'
  AND dMeeting < '2014-07-01 00:00:00.000' 
  AND bManaged = 'N'                

1 个答案:

答案 0 :(得分:1)

尝试表格表达式

WITH C AS (
SELECT lMeetingRegisterID
      ,sPlanNumber
      ,sName
      ,sDescription
      ,dMeeting
      ,sMeetingTime
      ,bManaged
      ,dFinalised

  FROM [Strata].[dbo].[MeetingRegister]
  inner Join MeetingType on MeetingRegister.lMeetingTypeID = meetingtype.lMeetingTypeID
  inner Join OwnersCorporation on MeetingRegister.lOwnersCorporationID =    OwnersCorporation.lOwnersCorporationID
  inner Join tbluser on OwnersCorporation.lUserID = tblUser.lUserID

  WHERE dFinalised = '1900-01-01 00:00:00.000'
  AND dMeeting < '2014-07-01 00:00:00.000' 
  AND bManaged != 'N'
)
Update C
set dFinalised = '2015-01-14 00:00:00.000'