[英]How to copy a column value to other column of same database table whenever a new record is inserted?
I have the following database table: 我有以下数据库表:
Book {Id(primary Key), Name, TotalNoOfCopies, NoOfCopiesAvailable}
I want that whenever a new record/row is inserted the column NoOfCopiesAvailabe contains the same value as in column TotalNoOfCopies. 我希望每当插入新记录/行时,列NoOfCopiesAvailabe包含的值与列TotalToOfCopies中的值相同。
I tried using the following successful trigger: 我尝试使用以下成功触发器:
for insert
as declare @id nvarchar(10),@name varchar(50),@author varchar(40),@totalNoOfCopies tinyint, @availableNoOfCOpies tinyint;
select @id=i.Id from inserted i;
select @name=i.Name from inserted i;
select @author=i.Author from inserted i;
select @totalNoOfCopies=i.TotalNoOfCopies from inserted i;
select @availableNoOfCopies=i.TotalNoOfCopies from inserted i;
delete from Book where Id=@id;
insert into Book values(@id,@name,@author,@totalNoOfCopies,@availableNoOfCOpies);
But it performs 3 transactions: 但它执行3笔交易:
1.For inserting a new record 1.用于插入新记录
2.For deleting that new record 2.用于删除该新记录
3.For inserting the new record that has NoOfCopiesAvailable=TotalNoOfCopies 3.用于插入具有NoOfCopiesAvailable = TotalNoOfCopies的新记录
For example: 例如:
Insert into Book values('123','Book','Author',5,null)
Messages: 讯息:
1 row(s) affected 受影响1行
1 row(s) affected 受影响1行
1 row(s) affected 受影响1行
I was wondering if there is any way of doing it in a single transaction? 我想知道单笔交易中是否有任何办法?
Do you need an INSTEAD OF INSERT trigger: 您是否需要INSTEAD OF INSERT触发器:
CREATE TRIGGER Book_i ON Book
INSTEAD OF INSERT
AS
BEGIN
INSERT INTO Book (
Id,
Name,
TotalNoOfCopies,
NoOfCopiesAvailable
) SELECT
Id,
Name,
TotalNoOfCopies,
TotalNoOfCopies
) FROM
INSERTED
END
GO
It is clear an elegant. 显然是优雅的。
我宁愿修复表设计,而改用NumberOfCopiesSold,默认情况下可以为0。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.