Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations strongm on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Having trouble creating a trigger 1

Status
Not open for further replies.

albitzt

Technical User
Sep 8, 2010
13
US
I have been working at this for an hour now and with no success.

--Table 1
tblSessions
session_id
login_time
user_name

--Table 2
tblLastLogin
user_name
last_login_date

Currently tblSessions gets cleared by a stored procedure. I don't want to modify any existing objects. I am looking to have a trigger occur after a record is inserted into tblSessions table to insert or update into the tblLastLogin.

EXAMPLE:
When the following information gets inserted I want it to create or update the entry as outlined in the table tblLastLogin

tblSessions
--------------------
Session_id login_time user_name
---------- ---------- ----------
15 2010-09-07 08:57:20.167 myuser

tblLastLogin
---------------------
user_name last_login_date
--------- ---------------
myuser 2010-09-07 08:57:20.167

 
Code:
CREATE TRIGGER t_tblSessions_Ins ON tblSessions
FOR INSERT 
AS
BEGIN
  UPDATE a
  SET a.last_login_date = b.login_time
  FROM tblLastLogin a
  INNER JOIN INSERTED b
    ON a.[user_name] = b.[user_name]

  INSERT INTO tblLastLogin
  SELECT a.[user_name], a.login_time
  FROM INSERTED a
  LEFT OUTER JOIN tblLastLogin b
    ON a.[user_name] = b.[user_name]
  WHERE b.[user_name] IS NULL
END
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top