简体   繁体   中英

Update a column of each and every newly inserted (same row) record on a table depends on another column value without Trigger and default constraint

I have a table with an identity column (say Column1 ) and an integer column Column2 (nullable)

While inserting a row into this table, if the value passed to the Column2 is null, copy the Column1 value. If not null value is passed as argument for column2 , retain the given value.

Only after the every insert, this check and update should be done.

But as per the instruction given to me, should not use default constraint and trigger (after insert).

This is for audit purpose. The record from this table will be moved/switched from one table to another table. The volume and transaction is very high (billions of records).

Can you help me on this?

Thanks, Baskaran

Insert into tablename (column1, columns2) Values (value1, ISNULL(Value2,value1))

我认为这是您所期望的。

If you really want to do this in a trigger, try something like this:

CREATE TRIGGER TrgAfterINsert
ON dbo.YourTable
AFTER INSERT
AS
    UPDATE t
    SET Column2 = i.Column1
    FROM dbo.YourTable t
    INNER JOIN Inserted i ON i.Column1 = t.Column1
    WHERE t.Column2 IS NULL

This basically updates the YourTable table after an INSERT , and any rows that were inserted with a NULL in column2 are updated so that column2 is equal to the column1 value for that row

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