Procedure/trigger SQL after inserting a row - sql

I'm not very keen in SQL. My plan is to create a trigger or a procedure in which a field of a table increments by 1 if I insert a row in another table.
For example: I create a row in Table1, so I increment +1 the field Table1Ocurrences in Table2.
The problem is that I don't know if the command AFTER INSERT is appliable in this case. Which sentences of code could I write?
Thank you.

sure you can:
create trigger trigger_update
on table1
after insert
as
begin
---do whatever you want
end
you can get the values from table1 inside your trigger by doing:
select * from INSERTED

Related

How to Retrieve the Identity column value in an insert trigger SQL Server

I have two tables that are identical except one has an identity column and the other doesn't. Instead the second table uses the value of the identity column from the first table. I thought I would insert into the second table as a trigger when a record is inserted into the first table. I cannot seem to get syntax right.
Null is being returned from the identity column #EDVisitId.
ALTER TRIGGER [dbo].[trgInserterrEDVisitOriginal] ON [dbo].[errEDVisit]
AFTER INSERT
AS
--Name: Bob Avallone
--Date: 6-15-2017
--
-- The purpose of this trigger is to insert a record into errEDVisitOriginal
-- whenever a new errEDVisit is inserted.
--XXXXXXXXXX
declare #EDVisitId int
declare #SubmissionControlID INT
Select #EDVisitId = EDVisitID from inserted
SELECT #SubmissionControlID = SubmissionControlID from Inserted
Begin
Insert Into errEDVisitOriginal (EDVisitId, SubmissionControlID)
VALUES (#EDVisitId, #SubmissionControlID )
End
Thanks for all the suggestions. I abandoned the idea of a trigger. Instead I simply insert the new records from the first table into the second one. See below.
Insert errEDVisitOriginal(EdVisitId, SubmissionControlID)
Select EdVisitId, SubmissionControlID
from errEDVisit where SubmissionControlID = #SubmissionControlID
you just need scope_identity()
Select #EDVisitId = scope_identity()
You can use SCOPE_IDENTITY to get the last inserted id from the first table put it into a variable then insert into the second table.
https://learn.microsoft.com/en-us/sql/t-sql/functions/scope-identity-transact-sql
Though the decision to duplicate information intentionally is dubious, you are vastly over-thinking the code. Just:
if exists (select * from inserted)
insert dbo.errEDVisitOriginal (EDVisitId, SubmissionControlID)
select EDVisitId, SubmissionControlID from inserted;

How to write a trigger to get before and after values in a single table

I have two tables transcriptTable and trancript_log.
I need to get before and after values in trancriptTable_log (OldValue,New,Value) when any update accrue on transcriptTable.
I have a trigger for before and after update but only one trigger at a time is executed.
Create trancriptTable_log table with required columns
create trigger below (one trigger is enough)
CREATE TRIGGER INSERTEDAndDELETEDTableExample
ON transcriptTable
FOR UPDATE
AS
BEGIN
--to get the old value (insert statement may vary depend on your need and table)
insert into trancriptTable_log (column_1) SELECT <your_column_name> FROM DELETED
--to get the new value
insert into trancriptTable_log values (column_2) SELECT <your_column_name> FROM INSERTED
END

ORACLE TRIGGER INSERT INTO ... (SELECT * ...)

Trigger with Insert into (select * ...)
I'm trying it.
INSERT INTO T_ USERS SELECT * FROM USERS WHERE ID = :new.ID;
not working...
this work.
INSERT INTO T_USERS(ID) VALUES(:new.ID);
Trigger
create or replace trigger "TRI_USER"
AFTER
insert on "USER"
for each row
begin
INSERT INTO T_USER SELECT * FROM USER WHERE ID = :new.ID;
end;​
this work.
INSERT INTO T_USERS(ID) VALUES(:new.ID);
So if it fits to you then try this:
INSERT INTO T_USER(ID) SELECT ID FROM USER WHERE ID = :new.ID;
If you want to select one or more rows from another table, you have to use this syntax:
insert into <table>(<col1>,<col2>,...,<coln>)
select <col1>,<col2>,...,<coln>
from ...;
Perhaps you could post the actual error you are experiencing?
Also, I suggest that you rethink your approach. Triggers that contain DML introduce all sorts of issues. Keep in mind that Oracle Database may need to restart a trigger, and could therefore execute your DML multiple times for a particular row.
Instead, put all your related DML statements together in a PL/SQL procedure and invoke that.
Its not about your trigger but because of INSERT statement
here insert statement works as below
INSERT INTO <TABLE>(COL1,COL2,COL3) VALUES (VAL1,VAL2,VAL3); --> If trying to populate value 1 by one.
INSERT INTO <TABLE>(COL1,COL2,COL3) --> If trying to insert mult vales at a time
SELECT VAL1,VAL2,VAL3 FROM <TABLE2>;
The number of values should match with number of columsn mentioned.
Hope this helps you to understand

How to write trigger to insert and update another table

I want to write trigger. When there is an entry in table1, table2 should get inserted with same values. And in some field in table1 is updated then respective field must get updated in table2. How can I know whether value is inserted or updated?
I am using inserted to insert value.
Please guide me.
Here is how you will know whether a value is inserted or updated in a trigger like this:
on INSERT, the inserted dynamic table is populated with the new values
on UPDATE, the inserted dynamic table is populated with the new values of the records that were updated, and the deleted dynamic table is poulated with the old values of the records that were updated
So basically, if the deleted table contains the id (assuming you have an id column) as in the inserted table, you can be assured that it was an UPDATE that caused the trigger. If the deleted table is empty, conversely, it was an INSERT.
use this trigger to solve your problem..
create TRIGGER [dbo].[insert_Assets_Tran]
ON [dbo].[AssetMaster]
AFTER INSERT , UPDATE
AS BEGIN
DECLARE #isnum TINYINT;
SELECT #isnum = COUNT(*) FROM inserted;
IF (#isnum = 1)
INSERT INTO AssetTransaction
select [AssetId],[Brandname],[SrNo],[Modelno],[Processor],[Ram],[Hdd],[Display],[Os],[Office],[Purchasedt]
,[Expirydt],[Vendor],[VendorAMC],[Typename],[LocationName],[Empid],[CreatedBy],[CreatedOn],[ModifiedBy]
,[ModifiedOn],[Remark],[AssetStatus],[Category],[Oylstartdt],[Oylenddt],[Configuration]
,[AStatus],[Tassign]
FROM inserted;
ELSE
RAISERROR('some fields not supplied', 16, 1)
WITH SETERROR;
END

How to Use FIRE_TRIGGERS in insert sql statement

I am trying to copy data from table "tb_A" to itself (with different primary key).
When "tb_A" table is insert new record, I have written a trigger to populate another table "tb_B" with one record.
I ran the following statement.
INSERT INTO [tb_A]
([NAME])
select top (20)[NAME] from [tb_A]
I was expected 20 new records in "tb_B". But I didn't.
Anyway I saw FIRE_TRIGGERS is using during bulk insert to overcome this issue.
is there is a any way to use it on inset statements too ? Please provide me example.
Gayan
Trigger code (copied from Gayan's comment to gbn's answer):
CREATE TRIGGER UpdatetbB ON [dbo].[tb_A] FOR INSERT
AS
DECLARE #AID as int
SELECT #AID = [ID] FROM inserted
INSERT INTO [tb_B]([IDA]) VALUES (#AID)
The reason your trigger did not work properly is because it is poorly designed. Triggers fire once for each insert even if you are inserting a million records. You havea trigger that makes the assumption it will owrk one record at a time. Anytime you set a value form inserted or deleted to a scalar variable the trigger is wrong and needs to be rewritten. Try something like this instead.
CREATE TRIGGER UpdatetbB ON [dbo].[tb_A] FOR INSERT
AS
INSERT INTO [tb_B]([IDA])
SELECT [ID] FROM inserted
FIRE_TRIGGERS is only for BULK INSERT (and bcp), not "standard" INSERT
I'd expect your trigger to look something like
CREATE TRIGGER TRG_tbA_I ON tb_A FOR INSERT
AS
SET NOCOUNT ON
INSERT tb_B (col1, col2, ...)
SELECT col1, col2, ... FROM INSERTED
GO
You use the special INSERTED table to get the list of new rows in tb_A, then INSERT from this into tb_B. This works for more than one row
If you add the trigger code then we can explain what went wrong.
Edit: your trigger will only read a single row (any row, no particular order) from INSERTED. It isn't set based like my rough example.