可以把SET IDENTITY_INSERT设置为On
下例创建一个含有标识列的表,并显示如何使用 SET IDENTITY_INSERT 设置填充由 DELETE 语句导致的标识值中的空隙。
-- Create products table.
CREATE TABLE products (id int IDENTITY PRIMARY KEY, product varchar(40))
GO
-- Inserting values into products table.
INSERT INTO products (product) VALUES ('screwdriver')
INSERT INTO products (product) VALUES ('hammer')
INSERT INTO products (product) VALUES ('saw')
INSERT INTO products (product) VALUES ('shovel')
GO
-- Create a gap in the identity values.
DELETE products
WHERE product = 'saw'
GO
SELECT *
FROM products
GO
-- Attempt to insert an explicit ID value of 3;
-- should return a warning.
INSERT INTO products (id, product) VALUES(3, 'garden shovel')
GO
-- SET IDENTITY_INSERT to ON.
SET IDENTITY_INSERT products ON
GO
-- Attempt to insert an explicit ID value of 3
INSERT INTO products (id, product) VALUES(3, 'garden shovel').
GO
SELECT *
FROM products
GO
-- Drop products table.
DROP TABLE products
GO
create trigger tg_t1 on t1
for insert
as
declare @max int,
@b varchar(10)
select @b=b from inserted
select @max=count(@@RowCount)from t1
update t1 set a=@max where b=@b
---------------------------
--test
insert into t1 values(5,'abc','desfff')
给你一个例子吧:做两个触发器
ALTER trigger 自增_简答题delete
on 简答题
for delete
as
declare @id int,@cnt int
select @cnt=count(*) from deleted
select @id=max(记录号) from deleted
begin
update 简答题 set 记录号=记录号-@cnt,@id=@id+1 where 记录号>@id
end
ALTER trigger 自增_简答题insert
on 简答题
after insert
as
if not exists(select * from 简答题)
begin
update 简答题 set 记录号=1
end
else
begin
update 简答题 set 记录号=(select count(*) from 简答题) where 简答题.题目 in (select
题目 from inserted)
end