How to Create Trigger Syntax in SQL

Database triggers run code when you update or insert a new record into a SQL Server database. You create a new trigger using SQL Server Management Studio's editor. Triggers have similar syntax to stored procedures, except the "trigger" keyword tells the database to store the code as a table trigger.

Instructions

    • 1

      Click the Windows "Start" button and select "All Programs" in the menu. Click "SQL Server," then click "SQL Server Management Studio." Click "New Query" to open the SQL editor.

    • 2

      Type the "create trigger" syntax. Type the following code to set up the trigger creation syntax:

      create trigger newtrigger

      ON customers

      Replace "customers" with the name of the table you want to use to run the trigger. For instance, if you want to run the trigger after a customer record is updated, you use the "customers" table.

    • 3

      Type the action that initiates the trigger. For instance, if you want to run the trigger after an insert and an update statement, type the following code:

      after insert, update

    • 4

      Type the code that executes when the trigger initializes. For instance, you can insert a second record after a customer record is entered. The following code inserts a customer order:

      insert into orders (order_item) values ('Widget Item')

      You can enter any SQL code into the code execution section of the trigger.

    • 5

      Press the "F5" key. The trigger code executes and the new trigger is created on the SQL server.

Related Searches:

References

Comments

Related Ads

Featured