首页 > 解决方案 > 如何修复:无法将值 NULL 插入列,插入失败

问题描述

对于学校,我正忙于在我的数据库上编写一个存储过程。现在,当我尝试执行它时出现错误。

我已经尝试查看堆栈溢出以进行修复,但找不到任何对我有帮助的东西。

create procedure spNieuweBestelling
    (@medewerkerid int,
     @productid int,
     @aantal_producten int)
as
begin
    declare @bestellingsid int
    declare @besteldatum date = getdate()

    select @bestellingsid = max(@bestellingsid) + 1
    from bestelling b;

    begin transaction
        insert into bestelling 
        values (@bestellingsid, @medewerkerid, @besteldatum)

        insert into productbestelling 
        values (@productid, @bestellingsid, @aantal_producten)

        if @@ERROR <> 0
        begin
            rollback
            raiserror ('error tijdens de 2de insert',16,1)
            return
        end
    end
    commit

exec spNieuweBestelling 2,2,200

表格截图:https ://prnt.sc/npqhiz

我希望此过程将插入到这 2 个表中,但它会不断引发此错误。

标签: sqlsql-serverstored-procedures

解决方案


我想你打错了:

select @bestellingsid = max(@bestellingsid) + 1
    from bestelling b;

应该是:

select @bestellingsid = max(bestellingsid) + 1
    from bestelling b;

但是你为什么不直接使用一个IDENTITY

另外,因为这是给学校的;当您插入表时,请始终列出列:

INSERT INTO productbestelling (productid, bestellingsid, aantal_producten)

推荐阅读