简体   繁体   中英

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.
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:
1.For inserting a new record
2.For deleting that new record
3.For inserting the new record that has NoOfCopiesAvailable=TotalNoOfCopies

For example:

Insert into Book values('123','Book','Author',5,null)

Messages:
1 row(s) affected
1 row(s) affected
1 row(s) affected


I was wondering if there is any way of doing it in a single transaction?

Do you need an INSTEAD OF INSERT trigger:

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。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM