错误消息213:列名或提供的值数与表定义不匹配

时间:2014-04-29 02:48:32

标签: sql-server stored-procedures

我创建了一个带有存储过程的表,我正在尝试将数据插入其中,但是我收到了这个错误

  

Msg 137,Level 15,State 2,Line 49
  必须声明标量变量“@EmployeeID”)

请帮忙!

Create Table Humanresource.Employee
(
    EmployeeID char(3) constraint pkemployeeid primary key,
    FirstName varchar(20) not null,
    LastName varchar(20) not null,
    Emp_Address varchar(30) not null,
    Title char(30) constraint ckTitle check(Title in ('Executive','Senior Executive','Management Trainee','Event Manager','Senior Event Manager')),
    Phone varchar(20) check(Phone like '[0-9][0-9]-[0-9][0-9][0-9][0-9]-[0-9][0-9][0-9]-[0-9][0-9][0-9]')
)

存储过程:

create procedure Auto_EmpID
    @FirstName varchar(20),
    @LastName varchar(20),
    @Address varchar(30),
    @Title varchar(30),
    @Phone varchar(20)
AS
   Declare @EmployeeID char(3)

   if exists (select EmployeeID From HumanResource.Employee Where EmployeeID = 'E101')
   BEGIN
      Select 
         @EmployeeID = Max(right(EmployeeID, 2))
      from HumanResource.Employee

      Select 
         @EmployeeID = CASE
                         When @EmployeeID >= 0 AND @Employeeid < 9 
                           Then 'E0' + convert(char(3), @EmployeeID + 1)
                         When @EmployeeID >= 9 AND @EmployeeID < 99  
                           Then 'E' + convert(char(3), @EmployeeID + 1)
                       END
    END
    Else
       set @Employeeid = 'E101'


    insert into HumanResource.Employee
    Values(@EmployeeID, @FirstName, @LastName, @Address, @Title, @Phone)

    Return 

    Exec Auto_EmpID 'Bamidele','Ajose','Lagos','11-1111-111-111'
    exec Auto_Empid 'Kunle','Awele','Ikeja','22-3332-655-897'
    exec auto_empid 'John','George','Benin','33-5555-7654-443'

    select * from humanresource.employee

    insert into humanresource.employee(@EmployeeID, @FirstName, @LastName, @Address, @Title, @Phone)
    values(@EmployeeID = 'e101', 'Baley', 'Carles', 'Los Angeles', '23-3445-434-344')

1 个答案:

答案 0 :(得分:1)

这两行存在很多问题:

insert into humanresource.employee(@EmployeeID,@FirstName,@LastName,@Address,@Title,@Phone)
values(@EmployeeID='e101','Baley','Carles','Los Angeles','23-3445-434-344')
  1. 您无需在@列前添加@符号前缀。这应该只与变量一起使用。
  2. 列列表包含6列,但您只在values子句中提供5个值。请添加第6个值或删除不想插入的列。
  3. 如果要使用值'e101',可以直接插入。如果你想使用变量@employeeID,只需传递它。赋值@employeeID = 'e101'values子句中是错误的。您可以set @employeeID = 'e101insert语句之前指定值。
  4. @employeeID被声明为char(3),因此即使您想在insert statement之前为其指定值'e101',该值也会被截断为'e10'。因此,您必须至少将其声明为char(4)
  5. 另一件事是你的存储过程需要5个输入参数,但在调用它时只传递4个。如果您只想传递一些参数而不是所有参数,则需要在创建过程时为每个参数指定默认值,如下所示:

    create procedure Auto_EmpID
    @FirstName varchar(20) = 'somefirstname',
    @LastName varchar(20) = 'somelastname',
    @Address varchar(30) = 'somecity',
    @Title varchar(30) = 'sometitle',
    @Phone varchar(20) = '111-111-111'