将带条件的输出添加到 SQL 中的存储过程?
Add output with condition to a stored procedure in SQL?
当我执行程序时,我填写了储备零件(机械车间)的 ID、零件数量和案例编号。
我正在尝试在某处添加一个输出,如果我 select 的零件数量 >= 库存零件数量,则会触发该输出,并输出一条消息“重新订购零件”
该脚本有效,只是它没有完成我需要的所有事情。
resid = reserve part id
antal = number of parts
sagsnummer = case number
Reservedele = spare parts
CREATE PROCEDURE sp_opret_forbrug
@resid int,
@antal int,
@sagsnummer int
AS
BEGIN
INSERT INTO dbo.forbrug (resid, antal, sagsnummer)
VALUES (@resid, @antal, @sagsnummer)
UPDATE [dbo].[Reservedele]
SET antal = Reservedele.antal - @antal
WHERE reservedele.resid = @resid;
END
--exec sp_opret_forbrug
--@resid = '49',
--@antal = '2',
--@sagsnummer ='11'
--drop procedure sp_opret_forbrug
您可以使用 THROW
抛出错误
CREATE OR ALTER PROCEDURE sp_opret_forbrug
@resid int,
@antal int,
@sagsnummer int
AS
SET XACT_ABORT ON;
BEGIN TRAN;
IF EXISTS (SELECT 1
FROM [dbo].[Reservedele]
WHERE reservedele.resid = @resid
AND Reservedele.antal < @antal)
THROW 50000, 'Not enough stock, reorder', 0;
INSERT INTO dbo.forbrug (resid, antal, sagsnummer)
VALUES (@resid, @antal, @sagsnummer)
UPDATE [dbo].[Reservedele]
SET antal = Reservedele.antal - @antal
WHERE reservedele.resid = @resid;
COMMIT;
当我执行程序时,我填写了储备零件(机械车间)的 ID、零件数量和案例编号。
我正在尝试在某处添加一个输出,如果我 select 的零件数量 >= 库存零件数量,则会触发该输出,并输出一条消息“重新订购零件”
该脚本有效,只是它没有完成我需要的所有事情。
resid = reserve part id
antal = number of parts
sagsnummer = case number
Reservedele = spare parts
CREATE PROCEDURE sp_opret_forbrug
@resid int,
@antal int,
@sagsnummer int
AS
BEGIN
INSERT INTO dbo.forbrug (resid, antal, sagsnummer)
VALUES (@resid, @antal, @sagsnummer)
UPDATE [dbo].[Reservedele]
SET antal = Reservedele.antal - @antal
WHERE reservedele.resid = @resid;
END
--exec sp_opret_forbrug
--@resid = '49',
--@antal = '2',
--@sagsnummer ='11'
--drop procedure sp_opret_forbrug
您可以使用 THROW
CREATE OR ALTER PROCEDURE sp_opret_forbrug
@resid int,
@antal int,
@sagsnummer int
AS
SET XACT_ABORT ON;
BEGIN TRAN;
IF EXISTS (SELECT 1
FROM [dbo].[Reservedele]
WHERE reservedele.resid = @resid
AND Reservedele.antal < @antal)
THROW 50000, 'Not enough stock, reorder', 0;
INSERT INTO dbo.forbrug (resid, antal, sagsnummer)
VALUES (@resid, @antal, @sagsnummer)
UPDATE [dbo].[Reservedele]
SET antal = Reservedele.antal - @antal
WHERE reservedele.resid = @resid;
COMMIT;