How to update values automatically in table 2, when new values occurs in table 1 - sql-server-2008

I am creating a query, wherein i have created select query from table 1 and then inserting values to table 2, but how can create a command that when new data comes in table 1 then update table 2 values
and this insertion happen daily with job.
I tried creating trigger but i don t know how i can relate this to my scenario
IF OBJECT_ID('TEMPDB..#temp')IS NOT NULL
DROP TABLE #temp
Select Getdate()[Data Till],Sum[Quantity] Qty
into #temp from XYZ w
here w.Date <=Getdate()
Insert into dbo.table1
Select [Data Till],Qty from #temp >
As of now data is coming in table 2 like
1)[Data Till]-2019/05/22 Qty-100
2)[Data Till]-2019/05/23 Qty-150
3)[Data Till]-2019/05/24 Qty-120
Now what if in 2019/05/22 back dated entry of qty -20 comes in table 1 and how will table 2 has to update values in table 2
1)[Data Till]-2019/05/22 Qty-80
2)[Data Till]-2019/05/23 Qty-150
3)[Data Till]-2019/05/24 Qty-120

CREATE TRIGGER [schema_name.]trigger_name
ON Table_name
AFTER INSERT
AS
BEGIN
-- write your update statement here
END
This is how you can write after update trigger that executes your statement between 'BEGIN' and 'END' when you insert new row into 'Table_name'.

AS MY ASSUMPTION
Update means you have the data in table 2 already. If the new data comes in table 1 what kind of update you want to do ?
is it existing data update or new record insert then update.
From your question if it is updated above two kinds of things can be happened
For this why you have two write insert trigger
create trigger abc
on table1
For insert
as
begin
--update table2
end

Related

how can i insert records of one table to another using trigger in mysql

i have 1 table as emp_demo and another table as emp_demos with same columns as
eg:
emp_demo_id|emp_demo_name
1 | xyz
i want to add AFTER INSERT trigger on emp_demo table so as soon as a record is inserted in emp_demo it should automatically get inserted into emp_demos table.
CREATE TRIGGER after_insert_trig
AFTER INSERT
ON emp_demo
FOR EACH ROW
BEGIN
INSERT INTO emp_demos(emp_demo_id, emp_demo_name)
VALUES(new.emp_demo_id, new.emp_demo_name);
END;
Demo.

MySQL Update Linked Table If Master Table Has New Records

I need to compare two tables that are linked by Foreign Key and add records from the master table that are not already in the linked table with foreign key. What's the best way to go about doing this please?
You can create a trigger on master table that will be triggered when there's a new insert to the master table.
DELIMITER //
CREATE TRIGGER master_after_insert
AFTER INSERT
ON linked_table FOR EACH ROW
BEGIN
-- Insert record into linked_table
INSERT INTO linked_table
( id,
some_value,
master_id)
VALUES
( 1,
'test value',
NEW.id ); // <-- using NEW you can get newly inserted record
END; //
this seemed to do the trick for me:
INSERT into table2 (foreignkey_id)
SELECT id FROM table1
WHERE id NOT IN (SELECT foreignkey_id FROM table2)

Updating other table column after insert in MySQL

I have these two table called "cases" and attendance respectively which has four columns:
cases-
id empid reaction date_t
1 EMP12654 interested 2017-09-22
attendance-
id empid logintime logouttime date_t flag workinghours call_att
1 EMP12654 00:14:49 05:14:49 2017-09-18 set 6 1
What I want to do is create a trigger on cases table that updates call_att column of attendance table with number of entries in reaction column of cases table, this is what I have tried so far
CREATE DEFINER=`root`#`localhost` TRIGGER `number_call`
AFTER INSERT ON `cases` FOR EACH ROW
BEGIN UPDATE attendance set call_att=call_att +1
WHERE empid=new.empid AND date_t=new.date_t; END
But that doesn't seem to work. I am quite new to triggers.
try this
CREATE TRIGGER number_call
AFTER INSERT ON cases
FOR EACH ROW
BEGIN
UPDATE attendance set call_att=(select count(*) from cases where empid=NEW.empid )
date_t=NEW.date_t;
END

Is it possible to find which tables have new data in the last n days?

My current project doesn't use any database migrations and so if any changes arise they are found manualy.
Is it possible to find out which tables in a database have new rows that were created in the last n days (for example 7 days)?
Thanks for any suggestions!
Create a Trigger for insert to make a value in the table for 1 as newly inserted or 0 it is inserted before .... its a flag that shows that a new value is added ... and then you can make an update statement to make sure that they are all take 0 value ... so that every time you insert in the table you add this column with 1
Example :
id StudentName flag
1 Frank 0
2 Andrew 1
insert into tablename(id,StudentName,flag) Values(3,'Alice',1)
always make the flag with 1 to know that it is a new record and it is recently added.
update tablename set flag = 0
this statment to make sure that all is inserted before and it is not new !!
Create A common table Which shows when table Update
Create table TableUpdatedRrecord (Table_Name varchar(max),Flag int,TableCreatedDate DateTime,Modified Date)
First Create table Which Has Record when New Rows were Inserted in table
Create table TableUpdatedRrecord (Table_Name varchar(max),Flag INT,TableCreatedDate DateTime,Modified DatetIME)
Now Create a Trigger for each table which is executed when table has a new insert
CREATE TRIGGER TriggerName
ON dbo.TableName
AFTER INSERT AS
BEGIN
DECLARE #CreatedDate datetime
Set #CreatedDate=(Select t.create_date from sys.tables t where name='TableName')
INSERT INTO TableUpdatedRrecord
(Table_Name,[Flag],[TableCreatedDate],[Modified])
VALUES
('TableName'
,1
,#CreatedDate
,GetDate())
END

MySQL insert in one of two tables based on condition for one table

Consider two tables that have timestamp and data columns. I need to construct an SQL that does the following:
Insert data (unique timestamp and data column) in one table if timestamp value is not present in the table ("insert my data in table 1 for timestamp="12:00 1999-01-01" only if that timestamp is not present in table 1...)
Otherwise, insert very same data in different table without any checks, and overwrite if necessary (... otherwise insert same set of fields in table 2).
How I could possibly achieve this on SQL? I could do it using a client but this is way slower. I use MySQL
Run a query for your 2nd bullet first. i.e. insert data into table 2 if it is present in table 1
insert into table2 (data, timestamp)
select 'myData', '12:00 1999-01-01'
from table1
where exists (
select 1 from table1
where timestamp = '12:00 1999-01-01'
)
limit 1
Then run your the query for your 1st bullet i.e. insert into table1 only if the data doesn't already exist
insert into table1 (data, timestamp)
select 'myData', '12:00 1999-01-01'
from table1
where not exists (
select 1 from table1
where timestamp = '12:00 1999-01-01'
)
limit 1
Running both these queries will always only insert 1 row into 1 table because if the row exists in table1, the not exists condition of the 2nd query will be false and if it doesn't exist in table1, then the exists condition of the 1st query will be false.
You may want to consider creating a unique constraint on table1 to automatically prevent duplicates so you can use insert ignore for your inserts into table1
alter table table1 add constraint myIndex (timestamp);
insert ignore into table1 (data,timestamp) values ('myData','12:00 1999-01-01');
A regural INSERT statement can insert records into one table only. You have 2 options:
Code the logic within the application
Create a stored procedure within mysql and code the application logic there
No matter which route you choose, I would
Add a unique index on the timestamp column in both tables.
Attempt to insert the data into the 1st table. If the insert succeeds, everything is OK. If the timestamp exists, then you will get an error (or a warning depending on mysql confioguration). Your solution handles the error (in mysql see DECLARE ... HANDLER ...).
Insert the data into the 2nd table using INSERT INTO ... ON DUPLICATE KEY UPDATE ... statement, which will insert the data if the timestamp does not exists, or updates the record if it does.