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

如何将SQL Server存储过程计算结果插入dbo.Store表Inventory列?

Fixing Your Stored Procedure to Update/Insert Inventory Values

Hey there! Let's get your stored procedure working the way you need it to—right now it only selects the calculated Inventory value, but doesn't actually write that value into the dbo.Store table's Inventory column. Here's how to adjust it based on your actual goal:

Option 1: Update Existing Rows (Most Likely What You Need)

If you want to set the Inventory column for every existing row in dbo.Store to the difference between Stock and Spoilage, use this updated procedure:

ALTER PROCEDURE [dbo].[sp_StoreBilling]
AS
BEGIN
    SET NOCOUNT ON;

    -- Update the Inventory column directly with the calculated difference
    UPDATE dbo.Store
    SET Inventory = Stock - Spoilage;

    -- Optional: Return the updated rows to verify changes
    SELECT Stock, Spoilage, Inventory
    FROM dbo.Store;
END

Key Notes:

  • I renamed the procedure from sp.StoreBilling to sp_StoreBilling—using dots in object names can cause confusion in SQL Server (since dots are used to separate schemas and objects).
  • The original @Stock and @Spoilage variables were unnecessary; we can calculate the difference directly in the UPDATE statement for each row.
  • The SET NOCOUNT ON; line prevents extra "rows affected" messages from being returned, which is standard for stored procedures.

Option 2: Insert New Rows (If You Need to Add New Records)

If your goal is to insert new rows into dbo.Store using the calculated Inventory value (instead of updating existing ones), use this version. Note: This will duplicate existing rows with the calculated Inventory—add a WHERE clause if you only want to insert specific records:

ALTER PROCEDURE [dbo].[sp_StoreBilling]
AS
BEGIN
    SET NOCOUNT ON;

    -- Insert new rows with the calculated Inventory value
    INSERT INTO dbo.Store (Stock, Spoilage, Inventory)
    SELECT Stock, Spoilage, Stock - Spoilage
    FROM dbo.Store;

    -- Optional: Return the newly inserted rows
    SELECT * FROM dbo.Store WHERE Inventory = Stock - Spoilage;
END

Pick the option that matches your business logic, test it out, and you're good to go!

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.14 08:20:30