How to implement trigger after insertion? - sql-server

I have a column named htmlContent which stores HTML Content in table EEmailData and a column named EEmailDataID which is unique ID of this table or I can say primary key of this table.
Now what I want to do is I want to create a trigger which would get this primary key from this table and insert this EEmailDataID in column htmlContent on a specific location.
I think this would take place by SUBSTRING function. Can anybody suggest me some other solution?

For this you need to add an idwhere you want to replace the Primary key value
Eg: <a href="localhost:19763/BitBucket/GUEST/... ?GuestInviteFwd=uArAiAd
And use the following trigger
CREATE TRIGGER EEmailData_Trigg ON EEmailData
AFTER INSERT
AS
IF EXISTS (SELECT top(1)*
FROM EEmailData p
JOIN inserted AS i
ON p.EEmailDataID = i.EEmailDataID
)
BEGIN
DECLARE #html VARCHAR(MAX),#id INT
SELECT #html=htmlContent ,#id=EEmailData
FROM EEmailData
WHERE EEmailDataID =(SELECT TOP(1) EEmailDataID FROM inserted)
UPDATE EEmailData
SET htmlContent=REPLACE(#html,'uArAiAd',#id)
WHERE EEmailDataID=#id
END
Now after trigger uArAiAd is replaced by EEmailDataID
also you can achieve this without trigger.
Just do the following after insert.
DECLARE #html VARCHAR(MAX),#id INT
--insert statements
SET #id=SCOPE_IDENTITY()
SELECT #html=htmlContent ,#id=EEmailData
FROM EEmailData
WHERE EEmailDataID =#id
UPDATE EEmailData
SET htmlContent=REPLACE(#html,'uArAiAd',#id)
WHERE EEmailDataID=#id

Related

Reinsert primary key in the same record

I need to insert records into a production table. The problem is that one of the fields needs to be the same value as the primary key.
In the example below, the Insert query is dropping '99' into [AlsoMyID]. But that's just a placeholder. It needs to be whatever value is going into [MyID].
How do I write the Insert query so that the system will add the same PK value to both [MyID] and [AlsoMyID]?
Drop table #mylittletable
Create table #Mylittletable (
[MyID] int IDENTITY(1,1) NOT FOR REPLICATION NOT NULL,
[AlsoMyID] int,
[ActualData] varchar(1))
Select * from #Mylittletable
Insert into #Mylittletable values (99,'x')
Select * from #Mylittletable
If you're interested in the background, the developer is using AlsoMyID as a linking field so any number of records can be linked together using the original primary key value. That said, I have no control over the table structure.
Firstly, you cannot specify the value for identity column unless you use set identity_insert on. so according to your requirement, you need to insert the same value to AlsoMyID as MyID.
You can work it out as flowing:
insert into Mylittletable
select ##IDENTITY+1,'1'
With this trigger on the table you can insert anything on the alsoMyID-column and that will be overwritten with what get's set in the myID-column.
create trigger tr_Mylittletable ON Mylittletable
AFTER INSERT AS
BEGIN
declare #ID int = (select MyID from inserted)
update Mylittletable set AlsoMyID = #ID where MyID = #ID
END
NOTE: This only works when making inserts of one line at a time!

How can return identity column value from table and insert other table in SQL Server?

I'm beginner in SQL Server and in my database I have two tables:
Table 1 with an id type bigint identity(1, 1)
Table 2 with the columns name and table1ID.
I want to insert (into table 1) and generate an id value. Then I will insert that id value into table1ID of table 2.
i change table to this and write this query:
insert into Interconnect_Traffic_Analysis_MAIN (Code_Op,Name_Op,Shomare_Tel,Duration,table1ID>>table1 id must save in this column)
select t7,t8,t9,t10 from Interconnect_Traffic_Analysis_Temp;
But how can I implement that?
Try this:
-- declare a variable to hold your newly created IDENTITY value
DECLARE #Identity BIGINT
-- insert your values into the first table
INSERT INTO dbo.Table1(list-of-columns)
VALUES(list-of-values);
-- get the newly generated IDENTITY value into your variable
SET #Identity = SCOPE_IDENTITY();
-- use that variable in your second INSERT
INSERT INTO dbo.Table2(table1Id)
VALUES(#Identity)
Update:
With your updated question with the INSERT statement, use this code to include the #Identity value:
INSERT INTO dbo.Interconnect_Traffic_Analysis_MAIN(Code_Op, Name_Op, Shomare_Tel, Duration, table1ID)
SELECT
t7, t8, t9, t10, #Identity
FROM
Interconnect_Traffic_Analysis_Temp;
You can try this:
insert into TableOne values ('abc');
insert into tableTwo values ((select SCOPE_IDENTITY()));
select SCOPE_IDENTITY() goes give you the last inserted id.
See this SQL fiddle

Trigger on insert and update that adds modification date

I'm making a simple table with names, emails etc, but I also have a ModifiedDate. My idea is to use a trigger after both insert and update, and insert the current date. Thus if anyone does anything (except delete) to that column, the date should reflect that.
This is however not working.
CREATE TRIGGER ModDate
ON X
AFTER INSERT, UPDATE
AS
BEGIN
INSERT INTO X (ModifiedDate)
VALUES (GETDATE())
END
Now I have a couple of values that can't be null, and what this seems to do is try and create a new row. I would like it to insert the date into the row that is currently being acted upon, I have no idea how though. Also what if I add 5 rows at once ?
You need to join the inserted virtual table in the trigger to limit the rows that get updated to those actually changed. Try this:
CREATE TRIGGER ModDate
ON TableX
AFTER INSERT, UPDATE
AS
BEGIN
UPDATE X
SET ModifiedDate = GETDATE()
FROM TableX X
JOIN inserted i ON X.key = i.key -- change to whatever key identifies
-- the tuples
END
Like #ZoharPeled correctly pointed out in a comment below there's really not much point in having the trigger update the date on insert - it would be better to use getdate() as the default value on the column (or even as another column InsertedDate if you want to track when records were initially created) and have the trigger only modify the ModifiedDate column after updates.
See the documentation for more information on the inserted and deleted tables.
CREATE TRIGGER ModDate
ON TableX
FOR INSERT, UPDATE
AS
BEGIN
UPDATE TableX
SET ModifiedDate = GETDATE()
WHERE Id = (Select Id from Inserted)
END
If you don't have keys on the insert data and you are not in command of the sql to add a default on the modifieddate column, you can get the insert trigger where the modifieddate column is null:
CREATE TRIGGER ModDate
ON TableX
AFTER INSERT
AS
BEGIN
UPDATE tableX SET ModifiedDate = GETDATE() where modifieddate is null
END

how to fire a sql trigger whenever the password change

I have a table containing id, user_Name and password. I want to create the trigger which will fire when ever the password changes.
Suppose the table is:
create table reg
(
id int identity(1,1) primary key,
userName varchar(100),
pass varchar(100)
)
and I want to save userName, password, changeDate in to below table
create table regBackUp
(
id int identity(1,1),
regId foreign key references reg(id),
oldPass varchar(100),
changeDate date
)
Well, you need to create after update trigger on reg table.
In that trigger you need to write to table regBackUp records selected from table named deleted. It is special table available in that triggers and it will hold values of reg table just before update.
See MSDN for reference about syntax of create trigger expression.
Use this. TRIGGER
You can get the old values from DELETED table
CREATE TRIGGER trgTest ON regFOR UPDATE
AS
BEGIN
IF UPDATE(pass)
BEGIN
DECLARE #id AS INT
DECLARE #pass AS varchar(100)
SELECT #id = ID, #pass = pass FROM DELETED
INSERT INTO regBackUp (regId, oldPass, changeDate)
VALUES (#id, #pass, GETDATE())
END
END
Use After Update Trigger with Update() function to find out whether column is updated or not. From docs.
indicates whether an INSERT or UPDATE attempt was made on a specified
column of a table or view. UPDATE() is used anywhere inside the body
of a Transact-SQL INSERT or UPDATE trigger to test whether the trigger
should execute certain actions.
Create a After Update trigger like this.
CREATE TRIGGER reg_pass_trg
ON reg
after UPDATE
AS
BEGIN
IF UPDATE(pass) --Works only when pass is mentioned in update statement
INSERT INTO regBackUp
(regId,oldPass,changeDate)
SELECT ID,pass,Getdate()
FROM deleted
END
INSERT INTO namepassback
(username,
pass,
[date])
SELECT username,
pass,
Getdate()
FROM namepass
WHERE id = 1
use above query that will work same without creating trigger

After insert, update timestamp trigger with two column primary key

I have a simple details table like so:
listid
custid
status
last_changed
The primary key consists of both listid and custid.
Now I'm trying to setup a trigger that sets the last_changed column to the current datetime every time an insert or update happens. I've found lots of info on how to do that with a single PK column, but with multiple PKs it gets confusing on how to correctly specify the PKs from the INSERTED table.
The trigger has to work in SQL Server 2005/2008/R2.
Thanks for a working trigger code!
Bonus would be to also check if the data was actually altered and only update last_changed in that case but for the sake of actually understanding how to correctly code the main question I'd like to see this as a separate code block if at all.
Hmm.... just because the primary key is made up of two columns shouldn't really make a big difference....
CREATE TRIGGER dbo.trgAfterUpdate ON dbo.YourTable
AFTER INSERT, UPDATE
AS
UPDATE dbo.YourTable
SET last_changed = GETDATE()
FROM Inserted i
WHERE dbo.YourTable.listid = i.listid AND dbo.YourTable.custid = i.custid
You just need to establish the JOIN between the two tables (your own data table and the Inserted pseudo table) on both columns...
Are am I missing something?? .....
CREATE TRIGGER dbo.trgAfterUpdate ON dbo.YourTable
AFTER INSERT, UPDATE
AS
UPDATE dbo.YourTable
SET last_changed = GETDATE()
FROM Inserted i
JOIN dbo.YourTable.listid = i.listid AND dbo.YourTable.custid = i.custid
WHERE NOT EXISTS
(SELECT 1 FROM Deleted D Where D.listid=I.listid AND D.custid=i.custid AND (D.status=i.status)
Here i assuming that stasus column is not nullable. If yes, you should add additional code to check if one of columns is NULL
You can check every field in trigger by comparing data from inserted and deleted table like below :
CREATE TRIGGER [dbo].[tr_test] ON [dbo].[table]
AFTER INSERT, UPDATE
AS
BEGIN
DECLARE #old_listid INT
DECLARE #old_custid INT
DECLARE #old_status INT
DECLARE #new_listid INT
DECLARE #new_custid INT
DECLARE #new_status INT
SELECT #old_listid=[listid], #old_custid=[custid], #old_status = [status] FROM [deleted]
SELECT #new_listid=[listid], #new_custid=[custid], #new_status = [status] FROM [inserted]
IF #oldstatus <> #new_status
BEGIN
UPDATE TABLE table SET last_changed = GETDATE() WHERE [listid] = #new_listid AND [custid] = #new_custid
END
END

Resources