简体   繁体   English

使用存储过程向表中插入新数据

[英]Insert new data to a table with stored procedure

I tried to make a stored procedure the insert data to a table:我试图使存储过程将数据插入表:

create procedure AddEmployee
(
    @FirstName nvarchar(20)
    , @LastName nvarchar(20)
    , @BirthDate datetime
    , @Country nvarchar(15)
    , @City nvarchar(15)
)
as
    insert into Employees
    values (@FirstName, @LastName, @BirthDate, @Country, @City)
go

But when I run it I get the error message:但是当我运行它时,我收到错误消息:

Msg 213, Level 16, State 1, Procedure AddEmployee, Line 2 [Batch Start Line 17]消息 213,级别 16,State 1,过程 AddEmployee,第 2 行 [批处理开始第 17 行]
Column name or number of supplied values does not match table definition.列名或提供的值的数量与表定义不匹配。

I looked at this question but it didn't solve my problem: Create a stored procedure to insert new data into a table我看了这个问题,但它没有解决我的问题: 创建存储过程以将新数据插入表中

When using insert, always include the columns names:使用插入时,请始终包含列名称:

create procedure AddEmployee (
    @FirstName nvarchar(20) ,
    @LastName nvarchar(20) ,
    @BirthDate datetime,
    @Country nvarchar(15),
    @City nvarchar(15)
) as
begin
    insert into Employees (FirstName, LastName, BirthDate, Country, City)
        values (@FirstName, @LastName, @BirthDate, @Country, @City);
end;

Although SQL allows you to leave out the column names, you should include them as a best-practice.尽管 SQL 允许您省略列名,但您应该将它们包括在内作为最佳实践。 This is particularly important for those learning the language, so they learn the safer way to do things.这对于那些学习语言的人来说尤其重要,因此他们会学习更安全的做事方式。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM