SQL TRIGGER验证空域

时间:2015-03-09 09:37:30

标签: sql sql-server tsql

我有一个使用SQL Server的外部程序,该软件已经编写,所以我试图创建一个触发器,当状态变为3时验证所有字段都已填充,但即使我插入它也只验证第一个字段其中的东西,它一直在验证,但我已在那里输入信息

我的代码就像这样

ALTER TRIGGER [dbo].[VALIDATE] ON [dbo].[InvNum]
FOR UPDATE
AS
if (( select orderstatusid from inserted) = 3) AND ((select [DocType] from inserted) = 4)
BEGIN

        If((SELECT ucIDSOrd01Product from inserted) ='')
        begin
            RAISERROR ('Please enter Product Description', 12,1)
        end

        if((SELECT ucIDSOrd01LoadingPoint from inserted) = '')
        begin
            RAISERROR ('Please enter the Loading Point', 12,1)
        end

        If((SELECT ulIDSOrd02Units from inserted) ='')
        begin
            RAISERROR ('Please enter a Unit', 12,1)
        end
END

1 个答案:

答案 0 :(得分:1)

正如@a_horse_with_no_name已经提到的那样,每个UPDATE触发一次,而不是每行触发一次,所以你必须相应地编码。您还需要ROLLBACK来取消更新,单独使用RAISERROR是不够的。你的触发器应该看起来像这样;

ALTER TRIGGER [dbo].[VALIDATE] ON [dbo].[InvNum] FOR UPDATE AS
if (exists (select 1 from inserted where orderstatusid = 3 and [DocType] = 4))
BEGIN
    If (exists (SELECT 1 from inserted where isnull(ucIDSOrd01Product, '') = '' and orderstatusid = 3 and [DocType] = 4))
    begin
        RAISERROR ('Please enter Product Description', 12,1)
        rollback
        return
    end

    if ( exists (SELECT 1 from inserted where isnull(ucIDSOrd01LoadingPoint, '') = '' and orderstatusid = 3 and [DocType] = 4))
    begin
        RAISERROR ('Please enter the Loading Point', 12,1)
        rollback
        return
    end

    If (exists (SELECT 1 from inserted where isnull(ulIDSOrd02Units, '') = '' and orderstatusid = 3 and [DocType] = 4))
    begin
        RAISERROR ('Please enter a Unit', 12,1)
        rollback
        return
    end
END

但是,正如@a_horse_with_no_name也提到的,检查约束可能是更好的选择,它取决于您的整体系统设计。

alter table [dbo].[VALIDATE] add constraint CK_ucIDSOrd01Product check (isnull(ucIDSOrd01Product, '') <> '' or orderstatusid <> 3 or [DocType] <> 4)
alter table [dbo].[VALIDATE] add constraint CK_ucIDSOrd01LoadingPoint check (isnull(ucIDSOrd01LoadingPoint, '') <> '' or orderstatusid <> 3 or [DocType] <> 4)
alter table [dbo].[VALIDATE] add constraint CK_ulIDSOrd02Units check (isnull(ulIDSOrd02Units, '') <> '' or orderstatusid <> 3 or [DocType] <> 4)