SQL Server 插入因自动递增 ID 而失败(无法将 null 值插入列“id”)

问题描述 投票:0回答:1

我在尝试创建新的演出记录时遇到“插入失败”错误。错误信息是:

无法将空值插入到表“GigHub.dbo.Gigs”的“id”列中; 列不允许为空。插入失败。该系统已 终止。

我正在为期末项目开发一个校园演出查找应用程序。我有一个 Gigs 表,其中有一个 id 列,我打算将其自动递增。这是相关的表结构:

CREATE TABLE dbo.Gigs 
(
    id INT PRIMARY KEY,
    [title] NVARCHAR(MAX) NOT NULL,
    [description] NVARCHAR(MAX) NOT NULL,
    [location] NVARCHAR(MAX) NOT NULL,
    [gigType] INT NOT NULL,
    [startDate] DATETIME NOT NULL,
    [endDate] DATETIME NOT NULL,
    [rate] DECIMAL(10, 2) NOT NULL,
    [gigStatus] INT NOT NULL,
    [createdDate] DATETIME NOT NULL,
    [requirements] NVARCHAR(MAX),
     [gigPoser_id] INT FOREIGN KEY REFERENCES dbo.Users(id) --this holds the id of the user that posted the gig
);

我尝试通过使用以下语句将 id 列修改为自动递增来修复错误:

ALTER TABLE dbo.Gigs
    ALTER COLUMN id INT IDENTITY NOT NULL

我验证了

ALTER TABLE
语句在 SQL Server Management Studio 中成功执行。我的应用程序代码创建一个新的
GigModel
对象,并在调用与存储过程 (
CreateGig
) 交互以插入演出数据的方法 (
sp_InsertGigs
) 之前设置所有相关属性。

尽管

id
列自动递增,但什么可能导致插入失败?我需要在应用程序代码或存储过程中采取任何其他步骤才能正确处理自动递增 ID 吗?

如果您需要有关应用程序代码或存储过程逻辑的更多详细信息,请告诉我。我使用 SQL Server 2022 和 C# 与 Dapper 进行数据库交互。

编辑: 存储过程逻辑:

ALTER PROCEDURE [dbo].[sp_InsertGigs_2] 
    @title nvarchar(255),
    @description ntext,
    @location nvarchar(1000), 
    @type nvarchar(355),
    @start_date date,
    @end_date date,
    @rate decimal(10,2),
    @status nvarchar(355),
    @gigPoster_id int,
    @date_created datetime,
    @skills_required nvarchar(MAX),     

    @id int output
    AS
    BEGIN
        
        SET NOCOUNT ON;
        SET IDENTITY_INSERT dbo.Gigs ON;

        insert into dbo.Gigs(id, title, description, location, type, start_date, end_date, rate, status, gigPoster_id, date_created, skills_required)
        values(@id, @title, @description, @location, @type, @start_date, @end_date, @rate, @status, @gigPoster_id, @date_created, @skills_required);

        SET IDENTITY_INSERT dbo.Gigs OFF

        select @id = SCOPE_IDENTITY();      
    END
sql sql-server sql-insert dapper
1个回答
0
投票

您正在存储过程中设置

IDENTITY_INSERT ON
。完成此操作后,您必须为
@id
提供一个值。但是由于您的
@id
是一个
output
变量,因此当您运行
INSERT
时,它还没有值,因此会出现错误。

删除存储过程中的

SET IDENTITY_INSERT dbo.Gigs
语句,并从
id
语句中删除
INSERT

-- SET IDENTITY_INSERT dbo.Gigs ON;

insert into dbo.Gigs(title, description, location, type, start_date, end_date, rate, status, gigPoster_id, date_created, skills_required)
values(@id, @description, @location, @type, @start_date, @end_date, @rate, @status, @gigPoster_id, @date_created, @skills_required);

-- SET IDENTITY_INSERT dbo.Gigs OFF;
© www.soinside.com 2019 - 2024. All rights reserved.