24

I have the below trigger:

 CREATE Trigger enroll_limit on Enrollments
 Instead of Insert
 As
 Declare @Count int
 Declare @Capacity int
 Select @Count = COUNT(*) From Enrollments
 Select @Capacity = Capacity From CourseSections
 If @Count < @Capacity
 Begin 
      Insert Into Enrollments Select * From Inserted
 End
 GO

I'm getting an error msg saying:

'CREATE TRIGGER' must be the first statement in a query batch.

Mitch Wheat
  • 295,962
  • 43
  • 465
  • 541
zoe
  • 905
  • 5
  • 12
  • 18
  • Possible duplicate: http://stackoverflow.com/questions/10336384/dynamic-sql-error-create-trigger-must-be-the-first-statement-in-a-query-batch – WholeLifeLearner Feb 24 '17 at 13:25

2 Answers2

50

The error message "'CREATE TRIGGER' must be the first statement in a query batch." usually occurs when a preceding group (batch) of statements does not have a terminating GO

So, I would suggest adding add a GO to the end of the preceding batch's statements.

Mitch Wheat
  • 295,962
  • 43
  • 465
  • 541
0

If you are trying this from SQL Server Management Studio, here is another option which worked for me:

In the left pane, right-click on the database and select "New Query".

This connects you to the specific database. Now you can enter your create trigger statement as the first statement in the query window which opens. There is no need for a "use" command.

enter image description here

jdhildeb
  • 3,322
  • 3
  • 17
  • 25