You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

求助:使用存储过程向已创建的学生表插入数据的正确方法

修正后的学生表与插入数据存储过程

你的代码存在类型不匹配问题:存储过程中@student_age参数定义为varchar(100),但数据表中student_age字段是integer类型,插入时会引发类型转换错误。另外建议给student_id添加主键约束,保证学生ID唯一。

修正后的建表语句

CREATE TABLE students
(
    student_id   integer not null PRIMARY KEY, -- 添加主键约束确保ID唯一
    student_name varchar(100),
    student_age  integer,
    mobile_no    varchar(20)
);

修正后的存储过程

CREATE PROCEDURE sp_student
    (@student_id   int,
     @student_name varchar(100),
     @student_age  int, -- 修正为与表字段匹配的int类型
     @mobile_no    varchar(20)) 
AS
BEGIN
    SET NOCOUNT ON; -- 避免返回影响行数的额外提示信息
    INSERT INTO students (student_id, student_name, student_age, mobile_no)
    VALUES (@student_id, @student_name, @student_age, @mobile_no);
END;

调用存储过程插入数据

通过以下语句调用存储过程,插入单条学生数据:

-- 示例:插入ID为1、姓名张三、年龄20、手机号13800138000的学生
EXEC sp_student @student_id = 1, @student_name = '张三', @student_age = 20, @mobile_no = '13800138000';

如果需要批量插入,可以循环调用该存储过程,或者修改存储过程支持表值参数实现批量操作,以上是基础的单条插入实现。

内容的提问来源于stack exchange,提问作者erohsik k

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.05 17:40:31