发现重复

时间:2017-09-06 08:16:55

标签: sorting triggers insert ranking

以下设置:

  • 我有一个包含2列colA(datatype varchar)和colB的表 (datatype int)
  • colB被称为“rank”,它应该是唯一的(即1,2,3),不一定是

挑战:

如果用户将插入新行(或更新现有行)并分配新的(尚未存在的)等级(例如4)=>没问题。

但是:如果用户将插入已存在的新行(或更新现有的行)(例如2)=>在这种情况下,触发器应该将所有等级(即2和3)增加1。因此,2变为3,而3变为4。

CREATE TABLE Test (
colA varchar(5), 
colB int
)

INSERT INTO Test 
VALUES 
('Row1', 1),
('Row2', 2),
('Row3', 3)

然后

INSERT INTO Test
Values
('Row4', 2)

应该带来以下结果:

Row1 => 1
Row2 => 3
Row3 => 4
Row4 => 2

挑战2:如果排名存在差距,该怎么办,即

Row1 => 1
Row2 => 2
Row3 => 4

现在,当我想插入一个新行(例如Row4,2)时,该表应该如下所示:

Row1 => 1
Row2 => 3
Row3 => 4
Row4 => 2

有什么想法吗?我现在甚至不知道怎么处理这个......

1 个答案:

答案 0 :(得分:0)

终于发现了一些......你对此有何看法?建议改进?

--Create Table Test
create table Test (colA varchar(5), colB int)

insert into test 
values 
('Row1', 1),
('Row2', 3),
('Row3', 2),
('Row4', 5),
('Row5', 4)

--Create Trigger
Create TRIGGER [dbo].[tr_rank_insert]
ON [dbo].[Test] 
AFTER Insert
AS 

DECLARE 
    @newColA varchar(10), 
    @newColB int,
SET @newColA = (Select colA from inserted)
SET @newColB = (Select colB from inserted)

DECLARE @rankid int 
DECLARE rank_cursor CURSOR FOR
    SELECT colB 
    FROM Test 
    ORDER by colB asc

OPEN rank_cursor
FETCH NEXT FROM rank_cursor INTO @rankid

WHILE @@FETCH_STATUS = 0
BEGIN 
    IF (@rankid < @newColB)
        FETCH NEXT FROM rank_cursor INTO @rankid

    ELSE  
        BEGIN 
            UPDATE Test 
            SET ColB = ColB + 1
            WHERE ColA <> @newColA and ColB >= @newColB

        BREAK

     END 

    FETCH NEXT FROM rank_cursor INTO @rankid

END

CLOSE rank_cursor 
DEALLOCATE rank_cursor

--Test
INSERT INTO Test Values ('Row6', 2)
INSERT INTO Test Values ('Row7', 5)