【问题标题】:'INSERT' stored procedure with validation带有验证的“INSERT”存储过程
【发布时间】:2020-08-31 15:40:16
【问题描述】:

我正在尝试创建一个存储过程,将新办公室插入到我数据库中的OFFICE 表中。

我想首先检查我尝试创建的办公室是否已经存在。

这是我到目前为止所获得的一些代码,但我无法完全正确。我将不胜感激一些意见。

CREATE PROCEDURE stored_proc_new_office
AS 
BEGIN    
    DECLARE @office_id int
    SELECT @office_id = (SELECT office_id FROM inserted)

    IF NOT EXISTS (SELECT 1 FROM OFFICE WHERE office_id = @office_id)
    BEGIN
        ROLLBACK TRANSACTION
        PRINT 'Office already exists.'
    END
END

【问题讨论】:

  • 存储过程?还是触发器? inserted 仅在触发器中可用。
  • 并且假设id无论如何都将始终是唯一的,因为它应该是系统生成的。我们需要知道您检测重复记录的实际标准,例如OfficeName 或类似的。而如果您希望在该SP中创建新记录,则需要在使用参数时传递创建新办公记录所需的信息。
  • 我猜两者都有可能,但是,我在这里找到的:link,他们正在使用插入。你的意思是为了验证我需要触发器吗?是的,你是对的,它应该是办公室名称而不是 id。
  • 不,您可以创建一个带有验证的 SP……只是不是您现在的方式。您需要查看名为“Insert Statements With Parameter”的示例,然后将有关您的新办公室的详细信息传入,然后在插入之前检查它是否已经存在。

标签: sql sql-server database tsql stored-procedures


【解决方案1】:

这是一个简单的示例,说明如何使用存储过程插入一条新记录,并检查以确保它不存在。

create procedure dbo.AddNewOffice
(
    @Name nvarchar(128)
    -- ... add parameters for other office details
    , @NewId int out
)
as 
begin
    set nocount on;

    insert into dbo.Office([Name]) -- ... add additional columns
    select @Name -- ... add additional parameters to match the columns above
    where not exists (select 1 from dbo.Office where [Name] = @Name); -- ... add any additional conditions for testing for uniqueness

    -- If nothing inserted return an error code for the calling app to use to display something meaningful to the user
    if @@rowcount = 0 return 99;

    -- return the new id to the calling app.
    set @NewId = scope_identity();

    return 0;
end

【讨论】:

    猜你喜欢
    • 2021-11-01
    • 1970-01-01
    • 1970-01-01
    • 2015-08-16
    • 1970-01-01
    • 2020-06-07
    • 2016-06-15
    • 2014-08-17
    • 1970-01-01
    相关资源
    最近更新 更多