如何在SQL Server中重置自动增量列

时间:2015-12-02 07:05:31

标签: sql-server triggers

我有两列,其中一列是t1int类型),是自动增量,另一列是t2char类型)

我尝试执行插入查询

INSERT into test(t2) values('test1');
INSERT into test(t2) values('test2');
INSERT into test(t2) values('test3');

看结果如下

t1 | t2
----------
 1 | test1
 2 | test2
 3 | test3

我想编写一个触发器,如果​​我尝试执行删除查询,则重置自动增量

Delete from t1 
where t1 = 2;

我想要一个返回此结果的触发器:

t1 | t2
----------
 1 | test1
 2 | test3

请让我知道最好的方式!

我等你的回答

由于

2 个答案:

答案 0 :(得分:0)

您可以使用以下查询重置自动增量的数量

ALTER TABLE table_name AUTO_INCREMENT = value;

注意:自动增量值应大于或等于自动增量列的最大值。

您可以查看更多here

答案 1 :(得分:-1)

在自动增量字段中查找最高数字 要查找最大数字,请运行以下SQL命令:

SELECT MAX( `column` ) FROM `table` ;
 Replace 'column' with the name of the auto incrementing column. Replace    table with the name of the table.

重置自动增量字段 下一步是从第一个命令获取数字并从那里自动增加。因此,在该数字中添加一个并运行以下命令:

ALTER TABLE `table` AUTO_INCREMENT = number;
 Replacing 'number' with the result of the previous command plus one and      replacing table with the table name.

如果删除了表中的所有行,则可以运行alter table命令并将其重置为0.