自动根据Sql server 2005中的另一列增加列?

时间:2013-05-23 05:51:37

标签: sql triggers primary-key auto-increment

我在表格中有两个主键列。第二列基于第一列。我告诉你他们的数字,看看splr_Slno是基于splr_Id。

enter image description here

我向你展示了另一个例子

enter image description here

当我删除splr_Id'21'和splr_Slno'2'的记录时,它应该是这样的 enter image description here

下面有一个触发器

 ALTER TRIGGER [dbo].[trigger_i] 
 ON  [dbo].[table] 
 AFTER DELETE
 AS 
 BEGIN
SET NOCOUNT ON;
--Declarations
    declare @intSplrlid as int
    declare @autoSplrslno as int
    set @autoSplrslno=0
--Process
    set @intSplrlid = (select splr_Id from deleted)
    --set @autoSplrslno = (select splr_Slno from deleted)
    update dbo.table set splr_Slno = @autoSplrslno+1 where dbo.table.splr_Id =@intSplrlid;

END

删除第二条记录...,我想要的是删除记录时应自动生成splr_Slno

1 个答案:

答案 0 :(得分:0)

我认为以下代码应该可行。在不同的场景中尝试它。我刚刚实现了逻辑。没测试过。告诉我是否有任何错误。

ALTER TRIGGER [dbo].[trigger1] 
ON  [dbo].[table1] 
AFTER DELETE
AS 
BEGIN
    DECLARE @splr_Id INT, @increment INT = 1, @iterate_splr_Id int, @iterate_splr_Slno int
    SELECT @splr_Id = splr_Id FROM DELETED

    DECLARE cursorObj CURSOR LOCAL static FOR SELECT splr_Slno, splr_Id FROM dbo.table1 WHERE splr_Id = @splr_Id
    OPEN cursorObj
    FETCH NEXT FROM cursorObj into @iterate_splr_Slno, @iterate_splr_Id
    WHILE @@FETCH_STATUS = 0
    BEGIN
      UPDATE dbo.table1 SET splr_Slno = @increment WHERE splr_Id =@iterate_splr_Id and splr_Slno = @iterate_splr_Slno
      SET @increment = @increment + 1
    FETCH NEXT FROM cursorObj into @iterate_splr_Slno, @iterate_splr_Id
    END
    CLOSE cursorObj
    DEALLOCATE cursorObj
END