Trigger an Insert in another table when i insert a value on a table - sql

I have one table that I log the status from some services.
I need to trigger an insert in another table when this table A receive one insert with the value FALSE.
Let me try to explain a little more:
I Have one table EMAIL into which I insert emails that I want to send. I Have another table LOG that logs one service. If the table LOG receives one insert on field STATUS with the value FALSE I want to trigger one insert in the table EMAIL.

Hi Try this...........
-------------Sample Table
create table [log] (Id int,[status] varchar(10))
create table Email ([Status] varchar(10),id int)
go
------------ Trigger Creation
create trigger tri_log on log
for insert
as
insert into email(id,[status])
select a.[id],a.[status]
from inserted a where a.[status] = 'false'
go
------------------Sample Check
select * from [log]
select * from [email]
-----------insert records for test
insert into [log] values (1,'True')
insert into [log] values (2,'False')
----------verify result
select * from [log]
select * from [email]

Related

How to create trigger to check if table changed

I'm beginner and i trying to create trigger to check if table changed then i track the changed and insert it into another table
i created table called history and this is my code
create table history
(
ProjectNo INT ,
UserName NVARCHAR(50),
ModifiedDate date,
Budget_Old int,
Budget_New int,
)
and created this trigger
CREATE TRIGGER t1 on history
on project AFTER UPDATE
AS BEGIN
IF UPDATE(Project.Pnumber,Project.Budget)
INSERT INTO dbo.history (ProjectNo , Username,ModifiedDate,Budget_Old,Budget_New)
SELECT
d.ProjectNo, suser_name() ,GETDATE(),d.Budget,i.budget
FROM
Deleted d , inserted i
where d.projectno = i.projectno
END
i think my if statment is wrong but what i should do to make my query run right
to insert this values in history table ? plz help me and sorry for bad English
Triggers have access to two logical tables that have an identical structure to the table they are defined on which us Project as I assume.
INSERTED, which is the new data to go into the table
DELETED, which is the old data the is in the table
So You can get the old values in this way:
CREATE TRIGGER t1
ON dbo.Project AFTER UPDATE
AS
INSERT INTO dbo.history (ProjectNo , Username)
SELECT d.ProjectNo , d.Username
FROM DELETED d
If you need to just have one record for specific project in the table history, then you would use inner join based on the projectNo and update the history table accordingly.
ITS WORKS BUDDY ENJOY!!!!!!!!!!!
CREATE TRIGGER tRIGGERNAME1
BEFORE UPDATE on history
FOR EACH ROW
BEGIN
INSERT INTO dbo.history (ProjectNo ,Budget_Old,Budget_New)
VALUES(:OLD.ProjectNo,:OLD.Budget_Old,:NEW.Budget_New);
END;

SQL Server use SCOPE_IDENTITY() for insert into with select command

Hello I have one table whose name is
PERSO_DATA(Id,refPerso,,Col1,Col2,Col3,Col4,Col5)
and I have
PERSO_DATA_QUEUE(Id,refPersoData,refVideo)
Firstly I will insert to datas to PERSO_DATA then I will take Id of inserted data and isnsert to another table as refPersoData.
INSERT INTO PERSO_DATA(refPerso,Col1,Col2,Col3,Col4,Col5)
SELECT #refPerso,pa.Col1,pa.Col2,pa.Col3,pa.Col4,pa.Col5 FROM #PERSODATA pa
SET #refPersoData=SCOPE_IDENTITY()
When I write like that i insert all datas but can't take the Id for each data
INSERT INTO PERSO_DATA_QUEUE(refVideoQueue,refPersoData)
SELECT #refVideoQueue,#refPersoData
so code above it add only one.But I want if I have 10 data to insert PERSO_DATA I need to also insert PERSO_DATA_QUEUE table 10 data with inserted Ids.
How can I do this? I couldn't find a solution.
Thanks in advance
Try this code:
CREATE TABLE #temp ([Id] [bigint] NOT NULL);
INSERT INTO PERSO_DATA(refPerso,Col1,Col2,Col3,Col4,Col5)
OUTPUT INSERTED.Id
INTO #temp (Id)
SELECT #refPerso,pa.Col1,pa.Col2,pa.Col3,pa.Col4,pa.Col5
FROM #PERSODATA pa;
INSERT INTO PERSO_DATA_QUEUE(refVideoQueue,refPersoData)
SELECT #refVideoQueue, Id
FROM #temp;
The solution might be combining either cursor or loop and any iterator - like ROW_NUMBER() in your temp table.
Then - use SCOPE_IDENTITY() in it to get created IDENTITY value.

AUDIT TRAIL OF TABLES

I want to do audit trail on specific table like
what inserted,updated,deleted in table and all this logs are save in one table
I am using sql server 2012 .
Can any one please help me with how to achieve this?
Please note - Use of cursor is restricted
create an after trigger on that table and insert the records into the log table .
create trigger <trigger_name> after insert/update/delete/ on
table <orig table>
begin
insert into the log tables ('all the fields that you require');
end
Try using CDC (Change Data Capture). A very helpful tool which will help to manage the Audit Trail
Read the article from MSDN
This can be achieve using Triggers. Trigger will make your DML operations slower, if large Insert, Delete and Update operations are happening on your table. If it's small table you can create TRIGGER like below, to log the rows to another table based on the action occurred.
You can make use of Inserted and Deleted magic tables which hold the rows which are being Inserted and Deleted inside a trigger.
There is another alternate if you need more control over auditing using CDC (Change Data Capture).
CREATE TABLE TrailTable
(
Id INT,
Name VARCHAR(100)
);
CREATE TABLE TrailTableLog
(
Id INT,
Name VARCHAR(100),
Action CHAR(3)
);
Insert Into TrailTable VALUES (1,'Vi');
Insert Into TrailTable VALUES (2,'Vr');
Insert Into TrailTable VALUES (3,'An');
Insert Into TrailTable VALUES (4,'Ma');
CREATE TRIGGER dbo.TRG_IDU_TrailTable
ON dbo.TrailTable
AFTER INSERT, UPDATE, DELETE
AS
BEGIN
SET NOCOUNT ON;
DECLARE #Action as char(1);
SET #Action = (CASE WHEN EXISTS(SELECT * FROM INSERTED)
AND EXISTS(SELECT * FROM DELETED)
THEN 'U' -- Set Action to Updated.
WHEN EXISTS(SELECT * FROM INSERTED)
THEN 'I' -- Set Action to Insert.
WHEN EXISTS(SELECT * FROM DELETED)
THEN 'D' -- Set Action to Deleted.
ELSE NULL -- Skip. It may have been a "failed delete".
END)
IF(#Action = 'I')
BEGIN
INSERT INTO TRG_IDU_TrailTable (Id, Name, Action)
SELECT Id, Name, 'I' FROM INSERTED;
END
IF(#Action = 'D')
BEGIN
INSERT INTO TRG_IDU_TrailTable (Id, Name, Action)
SELECT Id, Name, 'D' FROM DELETED;
END
IF(#Action = 'U')
BEGIN
INSERT INTO TRG_IDU_TrailTable (Id, Name, Action)
SELECT Id, Name, 'U-D' FROM INSERTED; -- Records Deleted to Update
INSERT INTO TRG_IDU_TrailTable (Id, Name, Action)
SELECT Id, Name, 'U-I' FROM INSERTED; --Records Inserted to Update
END
END

Insert multiple records into table for each user in another table in SQL Server

I want to create notification application in node js and I just created a database with these three tables in SQL Server:
tbluser
user_id
user_name
tbluser_notification
user_id
noti_id
read
tblnotification
noti_id
noti_title
noti_mesg
noti_create
noti_sender_id
My question is: whenever I insert a notification into tblnotification, I want to insert a record for each user into the tbluser_notification.
Create after insert trigger
CREATE TRIGGER [dbo].[trgtblnotificationInsert]
ON [dbo].[tblnotification]
AFTER INSERT
AS
BEGIN
SET NOCOUNT ON;
INSERT INTO tbluser_notification (user_id, noti_id, notificationread)
SELECT tbluser.user_id, inserted.noti_id, 0
FROM tbluser
CROSS JOIN inserted
END
Please note: I have changed the column name 'read' to 'notificationread' as read is reserved word.

Table insertion by Trigger

Here's the table:
Order [OrderId], [DateTimePlaced], [ProductId], [Quantity]
Invoice [InvoiceId], [invoice_DateTime], [order_Id]
I want SQL Server automatically inserts the data into the Invoice table while I manually insert the data into Order table.
Here is my code:
create trigger invoice_Sync on Order
after insert
as
begin
insert into Invoice (invoice_DateTime,order_Id) select ID,Name,Address
select getdate(),OrderId
from inserted
go
However, after I executed this query, SQL Server gave me an error "The select list for the INSERT statement contains more items than the insert list"
My situation is: The invoice Id is set to be automatically incremented, So I think I should not manually put the Invoice Id into this trigger.
Any suggestions?
You have an extra SELECT there:
create trigger invoice_Sync on Order
after insert
as
begin
insert into Invoice (invoice_DateTime,order_Id)
--select ID,Name,Address, Why is this here?
select getdate(),OrderId
from inserted
end
go