SQL Server INSERT ... SELECT语句无法解析

时间:2012-10-25 08:15:12

标签: sql sql-server sql-server-2005 stored-procedures

我收到SQL Server 2005的以下错误消息

  

Msg 120,Level 15,State 1,Procedure EPIN,Line 37
   INSERT语句的选择列表包含的项目少于插入列表。 SELECT值的数量必须与   INSERT列的数量。

我已复制并粘贴选择列表并将列表插入Excel,并验证每个列表中的项目数相同。两个表中的附加主键字段未在insert语句或选择列表中列出。我不确定这是否相关,但可能是可疑的。

以下是我的存储过程的来源:

 set ANSI_NULLS ON
 set QUOTED_IDENTIFIER ON
 go

 -- =============================================
 -- Author:     Kristian Manuel
 -- Create date: 10/3/2012
 -- Description:    
 -- =============================================
 ALTER PROCEDURE [dbo].[EPIN] 
-- Add the parameters for the stored procedure here
     @PLUCODE varchar(30),      --Table tblPolicy
     @ECPAYFEES numeric(18,2),
     @COSTPAYABLE numeric(18,2),
     @RETAILPRICE numeric(18,2),
     @DENOMINATION varchar(50),
     @CARDNAME varchar(50),
     @DistributorID varchar(8),
     @AccntID decimal(18,0)

 --PO1  
 AS
 BEGIN
     -- SET NOCOUNT ON added to prevent extra result sets from
     -- interfering with SELECT statements.
     SET NOCOUNT ON;

     INSERT INTO [ECPAY-PC].[GENESIS].[dbo].[tblPolicy]
     ( 
       PolicyID                 ,
       AccountTID               ,
       DistributorID            ,
       CARDNAME                 ,
       DENOMINATION             ,
       RETAILPRICE              ,
       COSTPAYABLE              ,
       ECPAYFEES                ,
       PLUCODE 
     ) 
     SELECT 
         t.* 
     FROM
        (SELECT 
            AccountTID = @AccntID, 
            DistributorID = @DistributorID, 
            CARDNAME = @CARDNAME,      
            DENOMINATION = @DENOMINATION, 
            RETAILPRICE = @RETAILPRICE, 
            COSTPAYABLE = @COSTPAYABLE,      
            ECPAYFEES = @ECPAYFEES, 
            PLUCODE = @PLUCODE) t,
        [ECPAY-PC].[ECPNWEB].[dbo].[account] a
     WHERE
        a.AccntID = t.AccountTID --for account
 END

1 个答案:

答案 0 :(得分:4)

错误消息非常明确 - 您的INSERT语句需要 9列

   1. PolicyID                 
   2. AccountTID               
   3. DistributorID            
   4. CARDNAME                 
   5. DENOMINATION             
   6. RETAILPRICE              
   7. COSTPAYABLE              
   8. ECPAYFEES                
   9. PLUCODE 

要填写 - 但您的SELECT仅提供 8个值

   1. AccountTID               
   2. DistributorID            
   3. CARDNAME                 
   4. DENOMINATION             
   5. RETAILPRICE              
   6. COSTPAYABLE              
   7. ECPAYFEES                
   8. PLUCODE 

您似乎 PolicyID声明中为INSERT列(yoru SELECT中的第一列)提供任何值....

更新:如果目标表中的PolicyID列是“自动增量”(或IDENTITY)列,那么一定不能包含在您的INSERT声明中!

请使用:

 INSERT INTO [ECPAY-PC].[GENESIS].[dbo].[tblPolicy]
 (AccountTID, DistributorID, CARDNAME, DENOMINATION,
  RETAILPRICE, COSTPAYABLE, ECPAYFEES, PLUCODE)

    SELECT (that provides those 8 values) .... 

如果从PolicyID语句中省略INSERT,那么SQL Server将自动为其分配identity值,而您的INSERT .... SELECT语句将无效为INSERT提供8个值,期望8列......