1

我有一个查询要使用多个 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.

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

4

2 回答 2

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_GridMasterand的映射tbl_StoreGridMapping可能不存在(并且您想要一个nullfor StoreID,在这种情况下您可能希望将inner joins替换为right joins.

我还会询问将名为的列CityName转换为INT. 那里有些东西坏了(在命名中,如果没有别的)。

于 2013-04-15T06:58:12.317 回答
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
于 2015-04-08T17:07:26.160 回答