How can I validate data before insert/update with SQL Server?

我怕爱的太早我们不能终老 提交于 2019-12-01 12:31:41

This looks like a job for a check constraint, not a trigger:

ALTER TABLE [dbo].[ObjectRelationClauses]
ADD CONSTRAINT foreign_chk CHECK 
([ForeignPropertyId] IS NOT NULL OR [ForeignValue] IS NOT NULL);

You can add a constraint. However, if you are inserting multiple rows, then the constraint will prevent any rows from being inserted. To get around this, you can use an instead of trigger.

But, it might be easier simply to do:

insert into ObjectRelationClauses(. . .)
    select . . .
    from . . .
    where ForeignPropertyId is not null or ForeignValue is not null;

If you insert one row at a time, then the constraint is the way to go.

Because the SQL server dont know which record you are referring as per ForeignPropertyId and ForeignValue.

1) You should have taken use of the MAGIC TABLE. inserted.ForeignPropertyId is NULL AND inserted.ForeignValue is NULL.

2) You can use Instead Of trigger, not the For/After trigger.

If you are not that comfortable with trigger, my advice is not to use them too much. It will give you headache in the future.

RAISERROR Required Levels of Severity & State . Please use this query

CREATE TRIGGER [dbo].[Trigger_ObjectRelationClauses]
ON [dbo].[ObjectRelationClauses]
FOR INSERT, UPDATE
AS
BEGIN
    SET NoCount ON;
    DECLARE @ForeignPropertyId INT ,@ForeignValue varchar(255)
     Select @ForeignPropertyId=  i.ForeignPropertyId, @ForeignValue = i.ForeignValue from Inserted i
    IF(@ForeignPropertyId IS NULL AND @ForeignValue IS NULL)
    BEGIN
       RAISERROR ('Either ForeignPropertyId or ForeignValue must be provided to perform this action!',16,1)
    END

END

Why can't you USE SQL NOT NULL Constraint ?

The NOT NULL constraint enforces a column to NOT accept NULL values.

You can alter your existing column by referring below snippet.

ALTER TABLE [Table] ALTER COLUMN [Column] INTEGER NOT NULL;
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!