执行存储过程时出现“必须声明标量变量”错误

新手上路,请多包涵

我试图制定一个插入价格的程序:

 create procedure prInsertPrice
@NuggetID varchar(5),
@Unit_Price money,
@Start_Date datetime,
@End_Date datetime
as
begin
DECLARE @date AS DATETIME
SET @date = GETDATE()
    if
        (
        (@NuggetID like 'N[0-9][0-9]')
        and
        (@Unit_Price is not null)
        and
        (@Start_Date is not null)
        )
    begin
        print 'Insert Success'
        insert NuggetPrice (NuggetId, Unit_Price, Start_Date, End_Date)
        values (@NuggetID, @Unit_Price, @Start_Date, @End_Date)
    end
    else
    begin
        print 'Failed to insert'
    end
end

当我执行该过程时很好,但是当我像这样运行该过程时:

 EXEC prInsertPrice 'N01', 20000, @date, null

我收到错误消息:

必须声明标量变量@date。

为什么会这样,我该如何纠正这个问题?

原文由 Aditya Rizky 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 1.2k
1 个回答

其他两个答案已经就错误原因提供了足够的信息,所以我不打算谈论它。这是解决数据验证的不同方法

与其创建一个 Stored Procedure 来限制将错误数据插入表中,我建议您创建一个 Check constraint 来执行此操作

ALTER TABLE NuggetPrice
  ADD CONSTRAINT CK_NuggetPrice CHECK (NuggetID LIKE 'N[0-9][0-9]' AND Unit_Price IS NOT NULL AND Start_Date IS NOT NULL)

这将确保没有人在 NuggetPrice

原文由 Pரதீப் 发布,翻译遵循 CC BY-SA 3.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进