SQL Server,游标永无止境

时间:2017-03-13 18:58:17

标签: sql-server cursor

我的任务是无法添加包含名为pesel的某个属性的错误形式的行。首先我认为我应该编写一个触发器并且它工作正常但我被告知要将其更改为光标,因为当用户想要一次添加多个值时,插入将在第一个错误pesel处停止并且它不会检查其他。到目前为止,我想出了这个,但似乎它在我执行它之后永远不会结束。

DECLARE cursor_pesel CURSOR FOR 
     SELECT pesel FROM person;

DECLARE @pesel CHAR(11)
DECLARE @WEIGHTS as table (position INT IDENTITY(1,1), weight TINYINT)

INSERT INTO @WEIGHTS 
VALUES (1), (3), (7), (9), (1), (3), (7), (9), (1), (3), (1)

OPEN cursor_pesel
FETCH NEXT FROM cursor_pesel INTO @pesel

WHILE @@FETCH_STATUS = 0 
BEGIN
    IF (LEN(@pesel) != 11 OR (ISNUMERIC(@pesel) = 0))
        RAISERROR('BAD FORM OF PESEL',1,1)

    IF (SELECT SUM(CONVERT(INT, SUBSTRING(@pesel, position,1)) * weight) % 10
        FROM @WEIGHTS) != 0
        RAISERROR('BAD FORM OF PESEL',1,1)
END

CLOSE cursor_pesel

1 个答案:

答案 0 :(得分:2)

你忘了取下一个记录:

FETCH NEXT FROM cursor_pesel INTO @pesel


DECLARE cursor_pesel CURSOR
FOR SELECT pesel FROM person;
DECLARE @pesel CHAR(11)
DECLARE @WEIGHTS as table (position INT IDENTITY(1,1), weight TINYINT)
INSERT INTO @WEIGHTS VALUES (1),(3),(7),(9),(1),(3),(7),(9),(1),(3),(1)

OPEN cursor_pesel

FETCH NEXT FROM cursor_pesel INTO @pesel

WHILE @@FETCH_STATUS=0 
BEGIN

    IF (LEN(@pesel)!=11 OR (ISNUMERIC(@pesel)=0))
        RAISERROR('BAD FORM OF PESEL',1,1)

    IF (SELECT SUM(CONVERT(INT, SUBSTRING(@pesel, position,1))*weight)%10
        FROM @WEIGHTS)!=0
        RAISERROR('BAD FORM OF PESEL',1,1)

    FETCH NEXT FROM cursor_pesel INTO @pesel   <--------
END

CLOSE cursor_pesel