SQL过程错误 - INSERT语句包含的项目多于插入列表

时间:2015-11-03 07:31:03

标签: sql sql-server stored-procedures

错误:

  

Msg 121,Level 15,State 1,Procedure InsertNonExistingNode,Line 5   INSERT语句的选择列表包含的项目多于   插入列表。 SELECT值的数量必须与数量匹配   INSERT列。

SQL Management Studio中的过程:

USE NWatchEntitiesUnitTest
GO

CREATE PROCEDURE InsertNonExistingNode (@TableVariable dbo.NodeTableTable READONLY, @ScalarParameter nvarchar(255))
AS
BEGIN
INSERT INTO NWatchNodes WITH (ROWLOCK) (
      NodeTypeId,
      Location,
      DisplayName,
      AccessLevel,
      IsEnabled,
      CreatedOn,
      CreatedBy,
      ModifiedOn,
      ModifiedBy,
      NativeId,
      SourceId,
      Name,
      Alias) 

    SELECT 
    NodeTypeId,
    Name,
    Location,
      DisplayName,
      AccessLevel,
      IsEnabled,
      CreatedOn,
      CreatedBy,
      ModifiedOn,
      ModifiedBy,
      NativeId,
      SourceId,
      Name,
      Alias

    FROM @TableVariable t
        /*Left Join then where ID is null to make sure the record doesn't exists*/
        LEFT JOIN NWatchNodes PR WITH (NOLOCK) 
                                ON  PR.ID = @ScalarParameter
                                AND PR.Name = t.Name
        WHERE PR.ID IS NULL
END

GO

3 个答案:

答案 0 :(得分:2)

INSERT中有一个缺少的列,该列为NameName语句中有SELECT列,但INSERT中没有

要解决此问题,只需将Name放在NodeTypeIdLocation之间的插入语句中。

以下是删除错误的正确查询,但似乎您select的名称是两次,因此您要删除select语句中name之后的NodeTypeId列,或者您将其添加到插入内容中,请参见下面添加缺失的列。

INSERT INTO NWatchNodes WITH( ROWLOCK )
       ( NodeTypeId,
         Name, -->> This column is the cause of error, because its missing
         Location,
         DisplayName,
         AccessLevel,
         IsEnabled,
         CreatedOn,
         CreatedBy,
         ModifiedOn,
         ModifiedBy,
         NativeId,
         SourceId,
         Name,
         Alias
       )
       SELECT NodeTypeId,
              Name,
              Location,
              DisplayName,
              AccessLevel,
              IsEnabled,
              CreatedOn,
              CreatedBy,
              ModifiedOn,
              ModifiedBy,
              NativeId,
              SourceId,
              Name,
              Alias

答案 1 :(得分:1)

您的select子句有14列

      NodeTypeId,
      Name,
      Location,
      DisplayName,
      AccessLevel,
      IsEnabled,
      CreatedOn,
      CreatedBy,
      ModifiedOn,
      ModifiedBy,
      NativeId,
      SourceId,
      Name,
      Alias

但是你的INSERT只有13

  NodeTypeId,
  // You are missing Name here
  Location,
  DisplayName,
  AccessLevel,
  IsEnabled,
  CreatedOn,
  CreatedBy,
  ModifiedOn,
  ModifiedBy,
  NativeId,
  SourceId,
  Name,
  Alias

答案 2 :(得分:0)

您选择的列数多于在表格中插入的列数。您的select语句包含14列,但您的INSERT语句仅列出了13列。因此,SQL引擎无法映射SELECT语句中的最后一列。