Solved

Help with an SQL Trigger

Posted on 2009-07-09
5
233 Views
Last Modified: 2012-05-07
Hello,
This is the first time I'm trying to create a trigger on my database, and I'm having a hard time creating it. For some reason ,I can't seem to find any clear directions on this.

In any case, I have 2 tables:
ENROLLMENT:
USE [UserNameStore]
GO

/****** Object:  Table [dbo].[Enrollment]    Script Date: 07/09/2009 11:45:53 ******/
SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO

SET ANSI_PADDING ON
GO

CREATE TABLE [dbo].[Enrollment](
      [PermID] [varchar](50) NOT NULL,
      [CN] [varchar](6) NOT NULL,
      [DTS] [datetime] NULL
) ON [PRIMARY]

GO

SET ANSI_PADDING OFF
GO

ALTER TABLE [dbo].[Enrollment]  WITH CHECK ADD  CONSTRAINT [FK_Enrollment_Courses] FOREIGN KEY([CN])
REFERENCES [dbo].[Courses] ([CN])
ON UPDATE CASCADE
ON DELETE CASCADE
GO

ALTER TABLE [dbo].[Enrollment] CHECK CONSTRAINT [FK_Enrollment_Courses]
GO

ALTER TABLE [dbo].[Enrollment]  WITH CHECK ADD  CONSTRAINT [FK_Enrollment_UserStore] FOREIGN KEY([PermID])
REFERENCES [dbo].[UserStore] ([PermID])
ON UPDATE CASCADE
ON DELETE CASCADE
GO

ALTER TABLE [dbo].[Enrollment] CHECK CONSTRAINT [FK_Enrollment_UserStore]
GO


AND CourseRemoveQueue:
USE [UserNameStore]
GO

/****** Object:  Table [dbo].[CourseRemoveQueue]    Script Date: 07/09/2009 11:45:57 ******/
SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO

SET ANSI_PADDING ON
GO

CREATE TABLE [dbo].[CourseRemoveQueue](
      [PermID] [varchar](50) NULL
) ON [PRIMARY]

GO

SET ANSI_PADDING OFF
GO



I'm attempting to create a trigger where anytime Enrollment.PermID is deleted, that same PermID is inserted into CourseRemoveQueue.PermID

and anytime a PermID is added into Enrollment.PermID, delete the corresponding CourseRemoveQueue.PermID entry.

I have attempted to create the first trigger  as such, though I'm aware that there's major flaws in my code, so I can use some help here.

CREATE TRIGGER [dbo].[Enrollment_AddRemoveQueue] ON [dbo].[Enrollment]
ON DELETE

AS
SET NOCOUNT ON;
IF EXISTS(SELECT DELETED.PermID FROM DELETED)
      INSERT INTO dbo.CourseRemoveQueue (PermID) VALUES ('DELETED.PermID')

I'm not exactly sure how to insert the just-deleted value of PermID from the Enrollment table. With the way it is right now, I get the value "DELETED.PermID" inserted into CourseRemoveQueue.Permid. Obviously that's not what I'm looking for.

TiA for any help you may be able to provide.
Georges
0
Comment
Question by:cvservices
  • 3
  • 2
5 Comments
 
LVL 26

Accepted Solution

by:
Chris Luttrell earned 200 total points
ID: 24817177
I think this trigger will do what you want.
CREATE TRIGGER [dbo].[Enrollment_AddRemoveQueue] ON [dbo].[Enrollment] 

AFTER INSERT,DELETE
 

AS 

SET NOCOUNT ON;

IF EXISTS(SELECT DELETED.PermID FROM DELETED) 

      INSERT INTO dbo.CourseRemoveQueue (PermID) Select DELETED.PermID FROM DELETED

      

IF EXISTS(SELECT INSERTED.PermID FROM INSERTED) 

      DELETE FROM dbo.CourseRemoveQueue

      FROM INSERTED INNER JOIN dbo.CourseRemoveQueue ON INSERTED.PermID = dbo.CourseRemoveQueue.PermID

GO

Open in new window

0
 
LVL 1

Author Comment

by:cvservices
ID: 24817294
CGLuttrell. Thank you so much!
This works like a charm. Since I'm the curious type though, I was able to figure out what's happening up until the end of the first IF statement.

If it's not too much trouble, would you mind explaining the second IF statement syntax ? In particular, the 2 FROMs and the INNER JOIN ?
0
 
LVL 26

Expert Comment

by:Chris Luttrell
ID: 24817926
You can not delete from a joined table directly like this:
      DELETE FROM dbo.CourseRemoveQueue
      INNER JOIN INSERTED ON INSERTED.PermID = dbo.CourseRemoveQueue.PermID
but you can delete from one of the joined tables by referencing it again with the "DELETE FROM tablereference" like I used
      DELETE FROM dbo.CourseRemoveQueue
      FROM INSERTED INNER JOIN dbo.CourseRemoveQueue ON INSERTED.PermID = dbo.CourseRemoveQueue.PermID

I generally build my complex delete statements by first working on a select that will identify the records that need deleted with a
SELECT *
FROM table1 inner join table2 on col1 = col2 ....
and then when that returns just what I want to delete I change the SELECT * into DELETE FROM Table1 to do the actual delete.

I hope that makes sense and answeres your question.
0
 
LVL 1

Author Comment

by:cvservices
ID: 24817974
I think that does.
All of this is a bit overwhelming for me, because this is the first relational database that I'm designing. so some of the terminology and logic in SQL statements, especially when it's embedded in Triggers or Procedures, is hard for me to wrap my head around. I'll get there.

Thank you very much for the explanation though. It certainly helped.
The points are yours!
0
 
LVL 26

Expert Comment

by:Chris Luttrell
ID: 24818054
Thanks, glad I could help.  I follow Zones SQL Server 2008, SQL Server 2005 and MS SQL Reporting so post any other questions you come up with and I will gladly try to help.
0

Featured Post

How to improve team productivity

Quip adds documents, spreadsheets, and tasklists to your Slack experience
- Elevate ideas to Quip docs
- Share Quip docs in Slack
- Get notified of changes to your docs
- Available on iOS/Android/Desktop/Web
- Online/Offline

Join & Write a Comment

Suggested Solutions

Title # Comments Views Activity
How to query date ranges with SQL 6 24
SQL Help - 12 37
replication - alerts? 4 20
SQL to update characters in table column 6 28
CCModeler offers a way to enter basic information like entities, attributes and relationships and export them as yEd or erviz diagram. It also can import existing Access or SQL Server tables with relationships.
In this article we will get to know that how can we recover deleted data if it happens accidently. We really can recover deleted rows if we know the time when data is deleted by using the transaction log.
Video by: Steve
Using examples as well as descriptions, step through each of the common simple join types, explaining differences in syntax, differences in expected outputs and showing how the queries run along with the actual outputs based upon a simple set of dem…
Polish reports in Access so they look terrific. Take yourself to another level. Equations, Back Color, Alternate Back Color. Write easy VBA Code. Tighten space to use less pages. Launch report from a menu, considering criteria only when it is filled…

705 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

19 Experts available now in Live!

Get 1:1 Help Now