Lets have for example two tables: Table A and Table B which are in JOIN.
Table A:
id INT PK
attr1 INT
Table B:
id INT PK
table_A_id INT NOT NULL FK
attr1 INT
attr2 INT
Table Battr2
is computed as TableB.attr2 = TableA.attr1 * TableB.attr1
.
The requirement is the following:
- If a new record is inserted into Table B or an existing record is updated where the Table B
attr1
changes the Table Battr2
must be calculated/recalculated. - If Table A
attr1
is changed then corresponding Table Battr2
should be recalculated.
So I am dealing with dependency between attributes in computation.
What is the proper way to perform the calculations in MSSql? Maybe triggers?
1条答案
按热度按时间fhg3lkii1#
In SQL Server, you can use triggers to automatically perform calculations or actions when certain events occur, such as the insertion or update of records. For your specific case, you can use an AFTER INSERT, UPDATE trigger on TableB to recalculate attr2 based on the conditions you provided.
Example code: