SQL插入到子查询返回多个值的表中

时间:2014-10-06 08:58:18

标签: sql sql-server-2008 sql-insert

我有一个使用子查询来确定某些值的查询。当第二个子查询中只有一个结果时,它运行正常,但是当第二个子查询中有多个可能的结果时,它会失败并带有

  

Msg 512,Level 16,State 1,Line 1 Subquery返回的值超过1   值。子查询遵循=,!=,<,< =时,不允许这样做,   ,> =或当子查询用作表达式错误时。

我想为第二个子查询识别的多个值中的每一个插入一条记录。

我的代码如下:

Declare @RoomID char (11)
Select @RoomID = min (RoomID) from tbRoom
While @RoomID is not null
begin
INSERT INTO [dbo].[tbSurveyLocation]
   ([SurveyUID]
   ,[LocationParentID]
   ,[LocationID]
   ,[Comment]
   ,[SurveyParentTypeID]
   ,[CanSurvey]
   ,[Surveyed]
   ,[Status]
   ,[LastUpdate]
   ,[LastUpdateUser]
   ,[ClientCode])

VALUES

((SELECT SurveyUID FROM tbSurvey where SurveyTitle = 'CARLISLE PARK CRICKET PAVILLION')

,30

,(SELECT tbRoom.RoomID FROM         tbBuilding INNER JOIN
              tbBuildingLinkBusinessUnit ON tbBuilding.BuildingID = tbBuildingLinkBusinessUnit.BuildingID INNER JOIN
              tbBusinessUnit ON tbBuildingLinkBusinessUnit.BusinessUnitID = tbBusinessUnit.BusinessUnitID INNER JOIN
              tbFloor ON tbBuilding.BuildingID = tbFloor.BuildingID INNER JOIN
              tbRoom ON tbFloor.FloorID = tbRoom.FloorID
               WHERE tbBusinessUnit.BusinessUnitName like '%CARLISLE PARK CRICKET PAVILLION%')

,'',203 ,1,1,0,CONVERT(DATETIME, '10/01/2014 00:00', 102),'PDS 2014','~K2~')
end

我在这里检查了其他类似的答案,但根据我的情况找不到与各种子查询直接相关的任何内容。

1 个答案:

答案 0 :(得分:1)

我应该事先说明我不知道问题的大背景或需要插入多少条记录。但是,根据您发布的代码,这看起来可能更符合您的需求:

INSERT INTO [dbo].[tbSurveyLocation]
([SurveyUID]
,[LocationParentID]
,[LocationID]
,[Comment]
,[SurveyParentTypeID]
,[CanSurvey]
,[Surveyed]
,[Status]
,[LastUpdate]
,[LastUpdateUser]
,[ClientCode])

SELECT  -- I'm going to keep this subquery because it isn't clear whether tbSurvey 
        -- is related to the rooms and business units in any way.
       (SELECT   Top 1 -- this ensures you only get one record back
                 SurveyUID
        FROM     tbSurvey
        WHERE    SurveyTitle = 'CARLISLE PARK CRICKET PAVILLION'
        -- If it matters which row you get, you can sort the survey with an ORDER BY here.
        )
     , 30
     , tblRoom.RoomID
     , ''
     , 203
     , 1
     , 1
     , 0
     , CONVERT(DATETIME, '10/01/2014 00:00', 102)
     ,'PDS 2014'
     ,'~K2~'
FROM   tbBuilding 
    JOIN tbBuildingLinkBusinessUnit ON tbBuilding.BuildingID = tbBuildingLinkBusinessUnit.BuildingID 
    JOIN tbBusinessUnit ON tbBuildingLinkBusinessUnit.BusinessUnitID = tbBusinessUnit.BusinessUnitID 
    JOIN tbFloor ON tbBuilding.BuildingID = tbFloor.BuildingID 
    JOIN tbRoom ON tbFloor.FloorID = tbRoom.FloorID
 WHERE tbBusinessUnit.BusinessUnitName like '%CARLISLE PARK CRICKET PAVILLION%')

我刚才所做的将为您提供与业务部门相关的所有房间的记录" CARLISLE PARK CRICKET PAVILLION"。如果您只需要一个房间,则可以将目标列列表下的SELECT更改为SELECT TOP 1。 (这将为您提供符合条件的任意房间;如果您需要特定房间,例如ID最低的房间,请在末尾使用ORDER BY子句来控制哪个房间是"前1&#34 ;)

现在,如果您需要做一些事情,例如链接调查标题和业务单位名称,那么它们是相同的,并为所有调查/业务单位运行,而不仅仅是Carlisle Park,请在评论中告诉我。如果是这样,请告诉我您对相同调查标题(一个?多于一个?)的预期调查数量以及您对特定业务单位的预期房间数是否大于一。