根据输入计数返回范围序列?

时间:2016-06-24 09:40:07

标签: sql-server sql-server-2008 sql-server-2012 sql-server-2008-r2

我有一张下表,我的目的是根据StartCount变量值将EndCount@Count返回给用户。

默认情况下,表中的StartCount, CurrentCount SequenceMst将为1.

  

如果用户输入@Count = 10则代码应返回StartCount = 1和   EndCount = 10

     

如果下一位用户输入@Count = 10则代码应返回StartCount = 11EndCount = 20

     

如果下一位用户输入@Count = 20则代码应返回StartCount = 21EndCount = 40

我的输出首先返回1,10范围然后10,20,但应该是11到21,并且应该在CurrentCount列的表格中更新22。

CREATE TABLE SequenceMst
(
Id INT identity(1,1) primary key
,Code varchar(50)
,StartCount INT
,CurrentCount INT
);

insert into SequenceMst values ('ApForm',1,1);

select * from SequenceMst;

--My Code
DECLARE @Count as INT = 10; -- could be any number as input parameter

DECLARE @CurrentCount        AS INT     
       ,@StartCount          AS INT
       ,@UpdatedCurrentCount AS INT; 

    SELECT @CurrentCount = CurrentCount 
    FROM   SequenceMst
    WHERE  Code = 'ApForm';

    SELECT @UpdatedCurrentCount = (CurrentCount + @Count) - 1
    FROM   SequenceMst
    WHERE  Code = 'ApForm';

    UPDATE SequenceMst
    SET    CurrentCount = @UpdatedCurrentCount + 1
    WHERE  Code = 'ApForm';     

    SELECT @CurrentCount as StartCount, @UpdatedCurrentCount as EndCount;

0 个答案:

没有答案