T-SQL - 反复制触发器

时间:2015-05-12 21:57:05

标签: sql database sql-server-2008 tsql triggers

我需要编写一个触发器,以防止同时插入多个记录,并检查该位置是否已存在于数据库中。代码编译但它不能正常工作 - 即使我尝试添加不存在的地址,它也会显示错误消息

这是我的代码:

CREATE TRIGGER address_duplicate ON place
AFTER INSERT
AS
BEGIN
	DECLARE @counter INT
	SELECT @counter=COUNT(*) FROM place WHERE street IN (SELECT street FROM inserted) AND number IN(SELECT number FROM inserted)
	AND city IN(SELECT city FROM inserted) AND postcode IN(SELECT postcode FROM inserted)
	IF @counter>0
	BEGIN
	RAISERROR('This record is already in the database',1,1)
	ROLLBACK
	END
	IF @@ROWCOUNT>1
	BEGIN
	RAISERROR('You can add only one record at the same time',1,2)
	ROLLBACK
	END
END
GO

2 个答案:

答案 0 :(得分:3)

您识别重复位置的逻辑不正确。

尝试这样的事情:

istream

另外想让你知道,使用触发器来避免重复可能会非常昂贵。

答案 1 :(得分:1)

就个人而言,我会使用一个唯一约束,并且在插入时可能会使用TRY-CATCH,但是如果你真的想在触发器中执行它,那么试试这个:

CREATE TRIGGER address_duplicate ON place
INSTEAD OF INSERT
AS
BEGIN
    DECLARE @newValue TABLE (ID INT);

    IF @@ROWCOUNT > 1
    BEGIN
        RAISERROR('Insert cancelled. You can add only one record at the same time.',1,2);
    END
    ELSE
    BEGIN
        INSERT INTO place
        OUTPUT inserted.ID INTO @newValue
            SELECT *
            FROM inserted
            EXCEPT
            SELECT *
            FROM place
        IF (SELECT 1 FROM @newValue) IS NULL
            RAISERROR('Insert cancelled. This record is already in the database',1,1)
    END
END