在SQL Server中插入带有多个Select语句的语句

时间:2013-04-15 06:50:26

标签: sql-server-2008

我有一个查询,使用多个Select语句插入一些记录 我的查询如下

    INSERT INTO tbl_StreetMaster
    (
    StreetName,
    CityID,
    StartPoint,
    EndPoint, 
    StoreID,
    IsActive,
    CreationDate,
    CreatedBy
    )

    SELECT

    (SELECT a.StreetName,CAST(a.CityName AS INT),a.EndPointFrom,a.EndPointTo
     FROM #TempRecords a 
     WHERE NOT EXISTS
     (SELECT b.StreetID,b.StreetName FROM tbl_StreetMaster b 
   WHERE a.StreetName=b.StreetName and a.EndPointFrom=b.StartPoint and
   a.EndPointTo=b.EndPoint and CAST(a.CityName AS INT)=b.CityID and b.IsActive=1
     ))
     ,
     (SELECT  a.StoreID   FROM tbl_StoreGridMapping a
     inner join tbl_GridMaster b on a.GridID=b.GridID
      inner join #TempRecords c on b.GridCode=c.GridCode1
      WHERE NOT EXISTS
      (SELECT b.StreetID,b.StreetName FROM tbl_StreetMaster b
     WHERE c.StreetName=b.StreetName and c.EndPointFrom=b.StartPoint and
     c.EndPointTo=b.EndPoint and CAST(c.CityName AS INT)=b.CityID and b.IsActive=1))

     , 
     1,GETDATE(),100 

即使我的Select中有正确的列数,它也会一直给我错误

The select list for the INSERT statement contains fewer items
than the insert list. The number of SELECT values must match the number of INSERT 
columns.

任何人都可以帮忙解决这个问题。

2 个答案:

答案 0 :(得分:1)

您不能从子选择中返回多个列(因此系统可能假定每个子选择中有一列并且总共计算五列,并且不足以告诉您子选择只能返回1个值。

我不清楚为什么你还没有把它写成单个查询:

INSERT INTO tbl_StreetMaster
(
StreetName,
CityID,
StartPoint,
EndPoint, 
StoreID,
IsActive,
CreationDate,
CreatedBy
)
SELECT
    c.StreetName,CAST(c.CityName AS INT),c.EndPointFrom,c.EndPointTo,
    a.StoreID, 1,GETDATE(),100
FROM tbl_StoreGridMapping a
 inner join tbl_GridMaster b on a.GridID=b.GridID
  inner join #TempRecords c on b.GridCode=c.GridCode1
  WHERE NOT EXISTS
  (SELECT b.StreetID,b.StreetName FROM tbl_StreetMaster b
 WHERE c.StreetName=b.StreetName and c.EndPointFrom=b.StartPoint and
 c.EndPointTo=b.EndPoint and CAST(c.CityName AS INT)=b.CityID and b.IsActive=1)

除非tbl_GridMastertbl_StoreGridMapping的映射可能不存在(并且您想要null StoreID,在这种情况下您可能想要替换{{1}与inner join s。

的s

我还要查询将一个名为right join的列投射到CityName的智慧(在某个地方)。那里有些东西被破坏了(在命名时,如果没有别的话)。

答案 1 :(得分:0)

如果在选择

之间放置联合,则可以执行此操作 像这样:

INSERT INTO table(elem1,elem2,elem3) SELECT elem1,elem2,elem3 from table1 union select elem1,elem2,elem3 from table2 union select elem1,elem2,elem3 from table3