views:

314

answers:

2

I would to create a trigger for Sybase, but it shows an error.

What I want to do is, when a delete operation is done on the [student] table, to check whether there is any record related to student on [account], and if so, raise an exception.

There seems to be a lack of support by Sybase. Their official seem not people to visit.

*CREATE TRIGGER AccountChecker
BEFORE DELETE ON student
REFERENCING OLD AS old_student
FOR EACH ROW 
BEGIN
DECLARE @acc CHAR(4);
DECLARE @acc_not_null EXCEPTION FOR SQLSTATE '99999';

SELECT @acc=account.account_number FROM account
WHERE account.student_id = old_student.student_id;

   IF @acc IS NOT NULL
   BEGIN
    SIGNAL acc_not_null
   END

END*
+1  A: 

Doesn't Sybase support foreign keys?

Tom H.
+3  A: 

Sybase supports foreign keys and primary keys, both via procedures such as sp_primarykey and sp_foreignkey and via declarative SQL constraints. What you are seeking to do is exactly what a foreign key from [account] referencing [student] should do.

The Sybase SQL User Guide (Adaptive Server 15, if it matters) illustrates a 'delete restricted' trigger (with somewhat different indentation):

create trigger deltitle
    on titles
    for delete
    as
       if (select count(*)
               from deleted, salesdetail
               where salesdetail.title_id =
               deleted.title_id) > 0
       begin
           rollback transaction
           print "You cannot delete a title with sales."
       end

I'm not convinced that rollback is a good idea; an exception is probably better.

The notation you are trying to use hews more closely to the SQL standard than the documented Sybase-supported notation.

Jonathan Leffler
thank you, Jonathan LefflerIt's a good alternate solution.
SilverNight