I want to make a table audit/shadow table only when the email column of my table is updated - sql

when i update one row (email) the trigger sends all of the data to the shadow table I only want the one row that was updated what am i doing wrong in mt trigger code below?
CREATE TRIGGER AspNetUsersEmail_trigger
ON AspNetUsers
AFTER INSERT, UPDATE
AS
IF ( UPDATE (Email) )
BEGIN
INSERT INTO [dbo].[AspNetUserEmailAudit]([UserId],[UserName],[Email],[NormalizedEmail],[FirstName],[LastName])
SELECT Id,[UserName],[Email],[NormalizedEmail],[FirstName],[LastName] FROM AspNetUsers
END;
UPDATE [Elearn2].[dbo].[AspNetUsers]
SET Email = 'isaac#gmail.com'
WHERE [Id] = 'A1785377-E3BA-483A-8600-024CA5885951'

you should use inserted table:
CREATE TRIGGER AspNetUsersEmail_trigger
ON AspNetUsers
AFTER INSERT, UPDATE
AS
IF ( UPDATE (Email) )
BEGIN
INSERT INTO [dbo].[AspNetUserEmailAudit]([UserId],[UserName],[Email],[NormalizedEmail],[FirstName],[LastName])
SELECT Id,[UserName],[Email],[NormalizedEmail],[FirstName],[LastName]
FROM INSERTED
END;
read more about these special tables here

In MS SQL you have to select the data from the table inserted.
The tables deleted and inserted exists in triggers and contains the deleted and updated / inserted rows.

Related

SQL Server trigger validation to insert or update

I have to develop a trigger for multiple value update for the Change_Table that contains two columns Article_C (primary key) and Status_C. The trigger activates when the Status_C column is updated and it needs to either insert or update the Target_Tablewhich columns are Article_T (primary key) and Status_T.
The Status column for both tables is a NOT NULL int
For insert validation: insert all Change_Table values (Articles & Status) that do not exist into the Target_Table.
For update condition: if the articles exist in the Target_Table, pass the updated status value to that table.
Status values are 1 or 2.
My current implementation:
CREATE TRIGGER [dbo].[Article_Trigger]
ON [dbo].[Change_Table]
AFTER UPDATE
NOT FOR REPLICATION
AS
IF UPDATE (Status_C)
BEGIN
INSERT INTO Target_Table (Article_T, Status_T)
SELECT Article_C, Status_C
FROM Change_Table
WHERE NOT EXISTS (SELECT * FROM Target_Table
WHERE Change_Table.Article_C = Target_Table.Article_T
AND Change_Table.Status_C = Target_Table.Status_T)
END
This is a rough idea of the insert but it only works once when the Change_Table is first updated and the target table is empty. After that I get an error "Violation of PRIMARY KEY constraint" due to duplicate primary key after updating the status for a second time due to the insert condition.
Query that gave error after second execution:
update Change_Table set status_c = 1 where Article_C in (1000,1003)
How can I modify this query to implement the update status condition to this trigger?
I think you could use deleted or inserted tables. These 2 virtual tables are working nicely with trigger. In you example, you may not need deleted table as you are not logging the historical changes.
CREATE TRIGGER [dbo].[Article_Trigger]
ON [dbo].[Change_Table]
AFTER UPDATE
NOT FOR REPLICATION
AS
IF UPDATE (Status_C)
BEGIN
--insert if not exist
INSERT INTO Target_Table
SELECT A.Article_C, A.Status_C
FROM inserted as A --the updated records from the source table will exist in the inserted virtual table
LEFT JOIN Target_Table as B
ON B.Article_T = A.Article_C
WHERE B.Article_T IS NULL
--update if exist
UPDATE A
SET A.Status_T = B.Article_C
FROM Target_Table as A
INNER JOIN inserted as B --the updated records from the source table will exist in the inserted virtual table
ON B.Article_C = A.Article_T
END

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;

Re Increment the Primary Column after deletion of the record in table in Sql?

i want to do this one to my child table.
check the primary key.It does not contains Identity Specification.
when inserting data my table should be like this when i delete a record it should be shown below.
how can i do this after deleting the record i want to update the next rows ....,and the result should like below
how can i do this any ideas..., please this is important for me...,
Create a Trigger, that refreshes your data after the delete query runs:
CREATE TRIGGER [dbo].[TableDeleted]
ON [dbo].[Table]
AFTER DELETE
AS
BEGIN
BEGIN TRAN X
UPDATE Table SET Column1 WHERE...
COMMIT TRAN X
END
UPDATE dbo.table
SET splr_Slno=splr_Slno-1
WHERE
splr_Slno> #splr_Slno AND splr_Id= #Splr_Id

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

SQL Trigger to update a field on insert if the inserted value conflicts with the unique constraint

I have a Table called Albums which contains a field IsDeleted and a field "Name".
Name is a unique key. My Question is:
Can I create a trigger which updates IsDeleted to False if it is set to True and the same name is inserted into the table by the user?
Of course the insert statement should somehow be changed to an update statement.
I'm Using MSSQL 2008 and I'm very new to triggers and SQL ingeneral
Thanks for your help!
Yes, you can do this with an instead of trigger. Example:
create trigger albums_ins_trig on albums instead of insert as begin
-- update albums which already exist and are being inserted again
update albums set IsDeleted=0 where IsDeleted=1
and exists (select * from inserted where albums.name=inserted.name)
-- insert new albums
insert into albums select * from inserted
where not exists (select * from albums where albums.id=inserted.id)
end