我试图写一个触发器来搜索该列的重复项,然后插入一个值,以便我不能在列中具有相同的值

时间:2014-08-11 10:58:12

标签: sql

我是SQL 2008 R2的新手,我正在尝试编写一个触发器,在插入一个值之前在一个名为AlphanumericCol的列中搜索重复项,这样我就不能在列中使用相同的值

到目前为止我所拥有的:

ALTER TRIGGER DUPLICATES
ON  AMGR_User_Fields_Tbl

AFTER INSERT,
  UPDATE
AS

Declare @Counter integer
Declare @Value integer

set @Counter = (Select top 1 AlphanumericCol from AMGR_User_Fields_Tbl order by AlphanumericCol  desc); -- this will bring back the last record
set @Value = @Counter + 1;



IF EXISTS(select top 1 * from AMGR_User_Fields_Tbl order by AlphanumericCol desc)
 BEGIN
  RAISERROR('This row already exists in the table', 16, 1)
  ROLLBACK TRAN
 END;

但似乎不起作用

提前致谢

1 个答案:

答案 0 :(得分:0)

最佳解决方案可能是:

alter table AMGR_User_Fields_Tbl add constraint ... unique ( AlphanumericCol );

如果由于某种原因这不起作用,则必须在引发错误之前在表中查找特定值(如果存在行,则无论AlphanumericCol的值如何都会出现错误)。我不知道sql-server所以这可能包含错误,但是:

ALTER TRIGGER DUPLICATES
    ON  AMGR_User_Fields_Tbl
AFTER INSERT, UPDATE AS
    IF EXISTS(select 1 
              from AMGR_User_Fields_Tbl as x
              join inserted AS y 
                  ON x.AlphanumericCol = y.AlphanumericCol)    
    BEGIN
        RAISERROR('This row already exists in the table', 16, 1)
        ROLLBACK TRAN
    END;