-1

I have created two tables:

In the first table I want to store a computed result in the 3rd column

Table 1

num1|num2|num3

I want to have num3 = num1+num2, after every update, insert, delete

My second table is for a percent calculation, something like a wishlist

Table 2 

value|stored|left

I want to have left = stored/value, ie. a percentage of the amount stored vs the value of an item.

How can I set these values up to compute on update, insert, delete?

Original:

i have created two tabels, in first one i try to store the result in the 3'rd column ex: my tabel structure num1|num2|num3

where num3=num1+num2 ,after every update,insert,delete

second tabel is for a percent calculation, something like a wishlist structure: value,stored,left

where value = the value of the object u wanna buy, ex 1250 stored is the ammount that you saved for your wish left is the percent left to achive your goal

same problem like the first tabel

Aaron Dietz
  • 10,137
  • 1
  • 14
  • 26
Terchila Marian
  • 2,225
  • 3
  • 25
  • 48

2 Answers2

2

Creating a trigger will help update your table after insert or update on the table will help update column , assuming u have an ID column in the table

CREATE TRIGGER Insert_Update ON mytable
AFTER INSERT, UPDATE
AS
BEGIN
    SET NOCOUNT ON;

    IF 
        UPDATE (num3)

    BEGIN
        UPDATE dbo.Mytable
        SET num3 = i.num1 + i.num2
        FROM inserted i
        INNER JOIN mytable t ON i.MyID = t.MyID
        LEFT JOIN deleted d ON i.MyID = d.MyID
        WHERE d.MyID IS NULL AND i.ColumnB IS NOT NULL -- Row was inserted
            OR d.MyID IS NOT NULL -- Row was updated
    END
END
GO
Ven
  • 2,011
  • 1
  • 13
  • 27
0

It would be better if you store the num1 and num2 values in variables before setting num3. Unless you perform an INSERT first in the first two columns and then an UPDATE on the num3 column.

Sometimes a database isn't set for autocommit, so you'll need to force it and after that reuse the values.

Mayko Gob
  • 1
  • 1
  • You probably won't do what you want in one single statement, because the values you'll need aren't on the table yet. Try to insert the first values, and then use a TRIGGER AFTER INSERT to UPDATE the NUM3. Be sure to set the trigger only for "after insert" otherwise you'll get a loop. BEGIN DECLARE num1_v numeric(15,2) DECLARE num2_v numeric(15,2) DECLARE num3_v numeric(15,2) SELECT num1_v = NUM1, num2_v = NUM2 FROM inserted (or deleted) WHERE = UPDATE set NUM3 = num1_v + num2_v WHERE = END
    – Mayko Gob Jan 22 '18 at 16:18